I am making a word processor application in order to practise Java and I would like it so that when the user attempts to close the appliction, a JFrame will come up asking to save changes.
I was thinking about setDefaultCloseOperation() but I have had little luck so far. I would also like it to appear whent he user clicks the "X" on the top right of the window aswell if possible.
setDefaultCloseOperation() EXIT_ON_CLOSE — Exit the application. JFrame. HIDE_ON_CLOSE — Hide the frame, but keep the application running. JFrame. DISPOSE_ON_CLOSE — Dispose of the frame object, but keep the application running.
We can implement most of the java swing applications using JFrame. By default, a JFrame can be displayed at the top-left position of a screen. We can display the center position of JFrame using the setLocationRelativeTo() method of Window class.
What happen if setSize method is not called on JFrame? The default size of a frame is 0 by 0 pixels. The setVisible(true) method makes the frame appear on the screen. If you forget to do this, the frame object will exist as an object in memory, but no picture will appear on the screen.
For showing a JFrame, setVisible(true) is the correct (and besides the deprecated show()-method) also the only way of making it visible. For hiding a JFrame, setVisible(false) is correct (and again besides the deprecated hide() again the only way).
You can set the JFrame DefaultCloseOperation to something like DO_NOTHING, and then, set a WindowsListener to grab the close event and do what you want. I'll post an exemple in a few minutes .
EDIT: Here's the example :
public static void main(String[] args) {
final JFrame frame = new JFrame("Test Frame");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setSize(800, 600);
frame.addWindowListener(new WindowAdapter() {
//I skipped unused callbacks for readability
@Override
public void windowClosing(WindowEvent e) {
if(JOptionPane.showConfirmDialog(frame, "Are you sure ?") == JOptionPane.OK_OPTION){
frame.setVisible(false);
frame.dispose();
}
}
});
frame.setVisible(true);
}
import java.awt.event.*;
import javax.swing.*;
public class QuickGuiTest {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
final JFrame frame = new JFrame("Test Frame");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setSize(600, 400);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
int result = JOptionPane.showConfirmDialog(
frame, "Are you sure?");
if( result==JOptionPane.OK_OPTION){
// NOW we change it to dispose on close..
frame.setDefaultCloseOperation(
JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(false);
frame.dispose();
}
}
});
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With