Reputation: 7568
Sorry for the newbish question, but I am new to JStuff
. I have seen a bunch of different ways to remove a JButton, but none of them seem to be working. Can anyone tell me what I am missing here, please?
My actionPerformed is being called when I press the button, and my screen is changing like I want it, but the JButton exit
will not go away
JButton exit;
@Override
public void draw() {
exit = new JButton("Exit");
exit.setLayout(null);
exit.setBounds(new Rectangle(SCREEN.getWidth() / 2 + 50, SCREEN
.getHeight() - 50, SCREEN.getWidth() / 2 - 100, 50));
exit.setActionCommand("Exit");
exit.addActionListener(this);
frame.add(exit);
frame.repaint();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Exit")) {
frame.remove(exit);
frame.validate();
frame.repaint();
eraseEverythingAndPutSomethingNewUp();
System.out.println("This is being called.");
}
}
Upvotes: 0
Views: 62
Reputation: 347334
In the absences of an runnable example that demonstrates your problem, this example works...
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.UIManager;
public class TestFrame {
public static void main(String[] args) {
new TestFrame();
}
public TestFrame() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
final JButton btn = new JButton("Remove");
final JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(btn);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.remove(btn);
((JComponent)frame.getContentPane()).revalidate();
((JComponent)frame.getContentPane()).repaint();
}
});
}
});
}
}
Upvotes: 3