Step 1.
You should call the setDefaultCloseOperation
during initialization of your JFrame. This tells the system how it should respond when the 'X' (close) button of your JFrame is clicked.
It has an integer parameter that can take 4 possible values:
- DO_NOTHING_ON_CLOSE (defined in WindowConstants): Don't do
anything; require the program to handle the operation in the
windowClosing method of a registered WindowListener object.
- HIDE_ON_CLOSE (defined in WindowConstants): Automatically hide the
frame after invoking any registered WindowListener objects.
- DISPOSE_ON_CLOSE (defined in WindowConstants): Automatically hide and
dispose the frame after invoking any registered WindowListener
objects.
- EXIT_ON_CLOSE (defined in JFrame): Exit the application
using the System exit method. Use this only in applications.
It sounds like DISPOSE_ON_CLOSE
is what you are looking for - it will hide and dispose the JFrame on which the 'X' button was clicked.
So, in the initialization of your JFrame, call
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Further reading: https://docs.oracle.com/javase/tutorial/uiswing/components/frame.html
Step 2.
When you have your JFrame set up to be disposed on closing, you can also close it programmatically. You can use
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
as explained in this answer.
What happens then is that dispatchEvent
will send the WINDOW_CLOSING event to the frame. The system knows it should dispose the frame, because you told it to DISPOSE_ON_CLOSE.
So, you should put that command in the ActionListener for the button that you use to close the frame:
someButton.addActionListener(
new ActionListener( )
{
public void actionPerformed(ActionEvent e)
{
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
}
}
);
Together, these two things accomplish that your frame is closed from a button other than the normal 'X' closing button.