I want to call a method confirmExit()
when the red close button of the title bar of a JFrame is clicked.
How can I capture that event?
I'd also like to prevent the window from closing if the user chooses not to proceed.
I want to call a method confirmExit()
when the red close button of the title bar of a JFrame is clicked.
How can I capture that event?
I'd also like to prevent the window from closing if the user chooses not to proceed.
This may work:
jdialog.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.out.println("jdialog window closed event received");
}
public void windowClosing(WindowEvent e) {
System.out.println("jdialog window closing event received");
}
});
Source: https://alvinalexander.com/java/jdialog-close-closing-event
This is what I put as a menu option where I made a button on a JFrame
to display another JFrame
. I wanted only the new frame to be visible, and not to destroy the one behind it. I initially hid the first JFrame
, while the new one became visible. Upon closing of the new JFrame
, I disposed of it followed by an action of making the old one visible again.
Note: The following code expands off of Ravinda's answer and ng
is a JButton
:
ng.addActionListener((ActionEvent e) -> {
setVisible(false);
JFrame j = new JFrame("NAME");
j.setVisible(true);
j.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
setVisible(true);
}
});
});
If you also want to prevent the window from closing unless the user chooses 'Yes', you can add: