我遇到了这个问题。我想从 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
}
}
最佳答案
从可见 GUI 添加/删除组件时的基本代码是:
panel.remove(...);
panel.add(...);
panel.revalidate();
panel.repaint();
上面的代码应该在 ActionListener 中完成,而不是在 PaintComponent() 方法中完成。绘画方法仅用于绘画。
关于java - 无法移除组件并重新绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21243786/