Java Swing: adding confirmation dialogue for closing Window in JFrame

Post date: Apr 1, 2011 11:02:12 AM

For novice Java swing programmers, I am sure that you wanted to add a confirmation dialogue in your JFrame when the user clicks on the close button, right?

That sounds Greek.

To speak simply, you have created a swing window. And when the user clicks on close button, you want it to ask,

"Are you sure you want to close this window?"

Somewhat like this:

it is very easy actually. All you have to do (after creating your Jframe window)is to

-add a windowListener method in your JFrame

-use WindowAdapter inside to monitor WindowClosing

-override the WindowClosing method to do your desired thing.

Now, lets get to the code:

I hope you already know how to make windows in Jframe, but here is a short code to make one.

see this part?

We are telling the Jframe not to do anything when the close button is clicked on its own.

To put simply, we are taking the control away.

now, lets add the window Listener, window adapter, and overriding the window closing part:

    frame = new JFrame("Java Frame");

            frame.setSize(560, 300);

            frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

            // Create the object for the frame

            frame.add(firstPanel);

            frame.setVisible(true);

            frame.addWindowListener(new WindowAdapter() {

                  public void windowClosing(WindowEvent e) {

                        int confirmed = JOptionPane.showConfirmDialog(null,

                                    "Are you sure you want to exit?", "User Confirmation",

                                    JOptionPane.YES_NO_OPTION);

                        if (confirmed == JOptionPane.YES_OPTION)

                              System.exit(0);

                  } 

I have created a static method called exit which looks somewhat like this:

static void exit(JFrame j) {     j.dispose();    }

there you have it 

Hope you like this tutorial and it will come in handy for you :D