1

how would i get my program to work so that when a button is clicked it is removed?

here is the code:

//Mainmenu
JFrame frame1 = new JFrame();
Container pane = frame1.getContentPane();

JButton a = new JButton(new ImageIcon("path2img"));
BufferedImage a1 = ImageIO.read(new File("path2img"));

 public Menu() throws IOException {
     frame1.setSize(300, 450);
    frame1.setLocationRelativeTo(null);
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame1.setResizable(false);
    frame1.setVisible(true);
    pane.add(a);
    a.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent aa) {
            pane.remove(a);

        }


    });
            }

thanks

runit
  • 45
  • 1
  • 4

2 Answers2

5

Any time you add or remove a component to something that's already displayed on the screen, you must call (re)validate(); repaint();

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
0

If you just want to hide it and make it not visible. You can set its visible property to false.

public void actionPerformed(ActionEvent e) {
    a.setVisible(false);
}

Alternatively, repaint the panel holding the button after you remove it (if you really want to discard the button.)

public void actionPerformed(ActionEvent e) {
    pane.remove(a);
    pane.repaint();
}
user3437460
  • 17,253
  • 15
  • 58
  • 106