2012-03-16 62 views
1

我正在構建Java應用程序。 GameView有一個包含多個PawnViews的BoardView(在這個例子中只有一個)。在JPanel上更改位置JLabel重繪

例子:

public class GameView extends Frame 
    { 
     public GameView() 
     { 
      AWTUtilities.setWindowOpaque(this, false); 
      this.setUndecorated(true); 
      this.setLayout(null); 
      this.setResizable(false); 
      this._boardview = new BoardView(); 
      int x = 0; 
      int y = 0; 

      PawnView pv = new PawnView(); 
      this._boardview.AddPawn(pv, 10, 10); 

      this._boardview.MovePawn(pv, 20, 10); 
     } 
    } 

    public class BoardView extends JPanel 
    { 
     public BoardView() 
     { 
      this.setOpaque(false); 
      RepaintManager.currentManager(null).setDoubleBufferingEnabled(true); 
      this.setLayout(null);  
     } 

     @Override 
     public void update(Graphics g) 
     { 
      paint(g); 
     } 

     public void AddPawn(PawnView pawnview, int x, int y) 
     { 
      this.add(pawnview); 
      pawnview.setLocation(x, y); 
     } 

     public void MovePawn(PawnView pawnview, int x, int y) 
     { 
      pawnview.setLocation(x, y); 
      //this.repaint(); 
     } 
    } 

    public class PawnView extends JLabel 
    { 
     public PawnView() 
     { 
      this.setOpaque(false); 
      RepaintManager.currentManager(null).setDoubleBufferingEnabled(true); 
      this.setLayout(null); 
     } 
    } 

起初一切看上去很不錯(不MovePawn):

http://dl.dropbox.com/u/7438271/1.png

當我打電話MovePawn它看起來像:

http://dl.dropbox.com/u/7438271/2.png

我試着請撥打this.revalidate()this.updateUI()this.repaint(),this.paintImmediately()以各種形式,但它們都使情況變得更糟:整個JPanel獲得白色背景。

我也嘗試覆蓋JPanel的paintComponent函數也沒有效果。

這隻發生在Mac OS X(完全更新)上,但我也遇到了在Windows中重新繪製的一些問題。

任何人都可以請幫忙嗎?

+1

我認爲我們需要更多的信息能夠更好地幫助你。你能否儘可能簡化問題,甚至創建一個我們可以編譯和運行的最小代碼示例,它演示了你的問題,但是不包含與問題無關的多餘代碼,[sscce](http:// SSCCE)? – 2012-03-16 22:35:23

回答

3

你的代碼是不可運行,

1)不要混合AWT框架與Swing JComponents,不知道(沒有測試),但我認爲AWTUtilities僅供搖擺的JComponent,然後

public class GameView extends Frame 

可能是

public class GameView extends JFrame 

2)

this._boardview = new BoardView(); 

必須

BoardView _boardview = new BoardView(); 

3)爲什麼原因是有代碼行,

RepaintManager.currentManager(null).setDoubleBufferingEnabled(true); 

我看到代碼打印這裏是更快的打印關閉雙緩衝關閉,但價值currentManager(null),根本沒有按「T讓我的任何SENCE

4)從來不使用public void update(Graphics g),這種方法是在API內部使用,使用paintComponent代替

5)與JComponents使用Swing Timer移動與調用repaint()

6)JLabel是透明的默認情況下刪除this.setOpaque(false);

7)JLabel沒有得到任何imlemented LayoutManager,刪除this.setLayout(null);

+0

我知道我的代碼不可運行。這是一個例子,您可以瞭解我們如何構建它。 1. JFrame框架不會有所作爲 2. this._boardview是正確的,因爲我有一個全局變量BoardView _boardview。這僅僅是不存在的例子 3.好 4.我試過的paintComponent也但這並沒有改變仍然什麼也 5.我會檢查出 6.還好 7.沒事 – ydd1987 2012-03-16 20:38:56

+0

但不是我的問題的答案,這就是爲什麼顯示白色的痕跡。 – ydd1987 2012-03-16 20:44:07

+0

@yohannesdedope有沒有任何其他的答案取決於這裏的od代碼 – mKorbel 2012-03-16 21:35:35