无法删除组件并重新绘制

时间:2014-01-20 20:43:43

标签: java swing components repaint

我遇到了这个问题。我想从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
    } 
}

1 个答案:

答案 0 :(得分:1)

从可见GUI添加/删除组件时的基本代码是:

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

上面的代码应该在ActionListener中完成,而不是在paintComponent()方法中完成。绘画方法仅用于绘画。