Won Seok  Lee
Won Seok Lee

Reputation: 51

How can I remove JButton from JFrame?

I want to remove JButton when user click JButton.

I know that I should use remove method, but it did not work.

How can I do this?

Here is my code:

class Game implements ActionListener {

JFrame gameFrame;
JButton tmpButton;
JLabel tmpLabel1, tmpLabel2, tmpLabel3, tmpLabel4;

public void actionPerformed(ActionEvent e) {
    gameFrame.remove(tmpLabel1);
    gameFrame.getContentPane().validate();
    return;
}

Game(String title) {
    gameFrame = new JFrame(title);
    gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    gameFrame.setBounds(100, 100, 300, 500);
    gameFrame.setResizable(false);
    gameFrame.getContentPane().setLayout(null);

    tmpLabel4 = new JLabel(new ImageIcon("./images/bomber.jpg"));
    tmpLabel4.setSize(200, 200);
    tmpLabel4.setLocation(50, 100);
    tmpButton = new JButton("Play");
    tmpButton.setSize(100, 50);
    tmpButton.setLocation(100, 350);
    tmpButton.addActionListener(this);

    gameFrame.getContentPane().add(tmpLabel4);
    gameFrame.getContentPane().add(tmpButton);
    gameFrame.setVisible(true);
}
}

Upvotes: 2

Views: 25271

Answers (4)

Mohammadreza Khatami
Mohammadreza Khatami

Reputation: 1332

don't add your button to jframe but add each component you want!

public void actionPerformed(ActionEvent event)
{
   //gameFrame.getContentPane().add(tmpButton); -=> "Commented Area"
   gameFrame.getContentPane().validate();
}

or hide your button like this

public void actionPerformed(ActionEvent event)
{
   tmpButton.setVisible(false);
}

Upvotes: 0

hermit
hermit

Reputation: 1117

If hiding the button instead of removing works for your code then you can use:

public void actionPerformed(ActionEvent event){
   tmpButton.setVisible(false);
 }

for the button.But the button is just hidden not removed.

Upvotes: 6

varun
varun

Reputation: 1523

First of all in your actionPerformed method you need to check that the button is clicked or not. And if the button is clicked, remove it. Here's how :

if(e.getSource() == tmpButton){
   gameFrame.getContentPane().remove(tmpButton);
}

add this to your actionPerformed Method

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347334

The simplest solution might be to...

For example...

Container parent = buttonThatWasClicked.getParent();
parent.remove(buttonThatWasClicked);
parent.revaidate();
parent.repaint();

As some ideas...

Upvotes: 3

Related Questions