2011-03-13 91 views
3

我只是在Java中進入圖形,我有一個問題。我使用JPanel面板創建了一個JFrame窗口(NetBeans Designer),並在其上繪製了一些圖形。然後我添加了一個JButton,它改變了一個變量,這會改變JPanel上方塊的X位置。在Java中重繪圖形

在按鈕按下該代碼將執行:

drawObject.setX(150); 
drawObject.repaint(); 

drawObject是這個類的一個實例:

public class sola extends JPanel { 

    private int x = 10; 

    @Override 
    public void paintComponent(Graphics g){ 
     super.paintComponents(g); 
     super.setBackground(Color.WHITE); 

     g.setColor(Color.ORANGE); 
     g.fill3DRect(x, 160, 100, 50, true); 
    } 

    public void setX(int xX){ 
     x = xX; 
    } 
} 

現在,當我按下一個JButton,矩形並移動到新位置,但在舊的位置仍然可見。只有當我調整窗口的大小時纔會刷新,舊的矩形會消失。我怎樣才能解決這個問題,以便當我按下按鈕時,矩形只在新位置可見?

+0

爲了更快得到更好的幫助,請發佈SSCCE(http://pscode.org/sscce.html)。如果您有問題,請不要忘記添加問號(?)。 – 2011-03-13 12:00:24

+1

我對這個第一個問題是一個非常明確的問題。 – Chris 2011-03-13 12:02:20

回答

3

這是

super.paintComponent(g); 

super.paintComponents(g); // note the s at the edn 

兩者差別很大!第一個告訴你的JPanel完成通常由paintComponent方法執行的所有管家功能,包括重新繪製背景(項目的關鍵)。第二,你打電話的那個人沒有做任何上述功能。所以我的建議是在超級通話中擺脫尾隨的問題。

+0

這工作,謝謝! – Squeazer 2011-03-13 12:27:06

+0

不客氣 - 感謝您的反饋! – 2011-03-13 12:34:39

1

您可以使用以下方法JComponent的:(http://download.oracle.com/javase/6/docs/api/javax/swing/JComponent.html

void repaint(long tm, int x, int y, int width, int height) 
Adds the specified region to the dirty region list if the component is showing. 
void repaint(Rectangle r) 
Adds the specified region to the dirty region list if the component is showing. 

你可以叫那些之前redraw()

1

您可以使用repaint()方法做這件事。

如果在面板上使用paintComponent()。你應該在整個面板上照顧這幅畫。您的示例中沒有代碼需要注意刪除舊的繪製矩形。

我推薦爲您的矩形創建一個自己的組件。 (你可以從組件擴展),那麼你可以重寫這些類的paintComponent方法,就像你在面板中做的那樣。因爲小組應該充當一個容器組件。不像自己繪製矩形。

知道將這些組件的實例添加到普通的JPanel中。這應該會按預期進行更新。