Oana
Oana

Reputation: 1

How to close a single GUI when pushing a JButton?

I have written some coding that has a GUI that has an enter button that, when clicked, opens another GUI that I have created. The GUI that gets displayed after has also 2 buttons. One of them does the right thing and i want the second button to close the GUI, but ONLY the second one, so the first one should remain on screen. I used System.exit(0) but that closes bouth GUIs. Does anayone know what to write to close only one GUI ?

Upvotes: 0

Views: 191

Answers (2)

Ibrahim Naazir
Ibrahim Naazir

Reputation: 23

I assume you are talking about JFrames when you say GUI. JFrame has a method called setVisible().

https://docs.oracle.com/javase/7/docs/api/java/awt/Window.html#setVisible(boolean)

You can use setVisible(false) in that button and it should close the second JFrame

Upvotes: 0

camickr
camickr

Reputation: 324098

when clicked, opens another GUI that I have created.

The second "GUI" should be a JDialog, not a JFrame.

I used System.exit(0) but that closes bouth GUIs.

Instead you should use:

dialog.dispose();

so you will need a reference to the dialog. You can get a reference to the current window by using:

JButton button = (JButton)e.getSource();
Window dialog = SwingUtilities.windowForComponent( button );

Where the getSource() method is from the ActionEvent class of your ActionListener.

Or a better way is to simulate that the "Close" button of the dialog was clicked. Check out Closing an Application. The ExitAction in this link will dispatch an event to the dialog.

Note: you don't need to use the "CloseListener" from the link, only the ExitAction and then make sure you use the setDefaultCloseOperation(...) when you create the dialog.

Upvotes: 1

Related Questions