2014-01-20 35 views
0

我有這個問題。我想從JPanel中刪除所有現有組件,並在按鈕單擊後添加另一個新組件。現在,如果我點擊一個按鈕,它會在左上角添加相同的按鈕,但沒有任何東西可以再點擊了。無法刪除組件並重新繪製

public class MainPanel extends JPanel implements ActionListener{ 

private Image backgroundImage; 
private Image startScreen; 
private boolean gameStarted = false; 
private SingleplayerButton button1; 
private MultiplayerButton button2; 

public MainPanel() { 
    String imgUrl = "graphics/"; 
    try { 
     startScreen = ImageIO.read(new File(imgUrl+"start.png")); 
    } catch (IOException e) { 
     Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, e); 
    } 
    backgroundImage = startScreen; 
    this.setLayout(null); 
    button1 = new SingleplayerButton(this); 
    button1.addActionListener(this); 
    this.add(button1); 

    button2 = new MultiplayerButton(this); 
    button2.addActionListener(this); 
    this.add(button2); 
} 


@Override 
protected void paintComponent(Graphics g) { 
    if(gameStarted == false) { 
     g.drawImage(backgroundImage, 0, 0, null); 
    } else { 
     this.removeAll(); 
     this.setBackground(Color.WHITE); 
     this.revalidate(); 
    } 
} 

public void actionPerformed(ActionEvent e) { 
    if(e.getSource() == button1) { 
     gameStarted = true; 
     this.repaint(); 
     // something more 
    } else if(e.getSource() == button2) { 
     gameStarted = true; 
     this.repaint(); 
     // something more 
    } 
} 
+0

你能發佈一個實際的SSCCE嗎?這段代碼甚至不會編譯。 –

+0

也許內容並沒有消失,因爲你沒有調用super.paintComponent(g);在paintComponent方法的頂部。我同意下面的答案,如果你不需要圖形不會在paintComponent方法中刪除,重新驗證和重畫。在聽衆 –

+0

@FelipeO.Thomé中執行此操作時,paintComponent()方法不負責繪製面板的子項。 paint()方法繪製子節點。有關更多信息,請參閱[詳細瞭解繪製機制](http://docs.oracle.com/javase/tutorial/uiswing/painting/closer.html)。 – camickr

回答

1

時添加/從可見GUI刪除組件的基本代碼是:

panel.remove(...); 
panel.add(...); 
panel.revalidate(); 
panel.repaint(); 

上面的代碼應在的ActionListener來完成,而不是在的paintComponent()方法。繪畫方法僅適用於繪畫。

相關問題