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
}
}
你能發佈一個實際的SSCCE嗎?這段代碼甚至不會編譯。 –
也許內容並沒有消失,因爲你沒有調用super.paintComponent(g);在paintComponent方法的頂部。我同意下面的答案,如果你不需要圖形不會在paintComponent方法中刪除,重新驗證和重畫。在聽衆 –
@FelipeO.Thomé中執行此操作時,paintComponent()方法不負責繪製面板的子項。 paint()方法繪製子節點。有關更多信息,請參閱[詳細瞭解繪製機制](http://docs.oracle.com/javase/tutorial/uiswing/painting/closer.html)。 – camickr