Question

I've got this problem. I wanna to remove all existing components from a JPanel and add another new after button click. Now, if I click on a button, it will add the same button at a top left corner but nothing is clickable anymore.

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
    } 
}
Was it helpful?

Solution

The basic code when you add/remove a component from a visible GUI is:

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

The above code should be done in the ActionListener, NOT in the paintComponent() method. Painting methods are for painting only.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top