0

I decided to put "close" buttons on my JFrames. If I test just that JFrame by itself, it works fine, but when I try to close it after opening it through another class, it won't close.

Here is the code:

JButton btnClose = new JButton("Close");
btnClose.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        frame.dispose();
    }
});
btnClose.setBounds(282, 666, 96, 50);
contentPane.add(btnClose);

I have tried using frame.dispose() and frame.close() and super.dispose() but the only one that works is system.exit(0); but then that exits the whole program.

The issue:

  • If I test the JFrame by itself, the frame closes fine.
  • If I open the program and navigate to that specific JFrame, the close button does nothing.

Please advise.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
VaMoose
  • 1,391
  • 2
  • 11
  • 17

2 Answers2

1

Did you add a display statement in the ActionListener to make sure the code is being executed?

If the code is being executed, then the problem is probably that the frame variable has in invalid reference.

You don't need to keep a reference to the frame. Instead use something like:

Window window = SwingUtilities.windowForComponent( e.getSource() );
window.dispose();
camickr
  • 321,443
  • 19
  • 166
  • 288
0

Use setVisible(false); on the frame. Then call dispose.

user489041
  • 27,916
  • 55
  • 135
  • 204