Computer Science Canada

[Tutorial] SWING: Controlling window closing

Author:  Aziz [ Thu Aug 25, 2005 11:48 am ]
Post subject:  [Tutorial] SWING: Controlling window closing

I don't know how many of the people here get into SWING, or if this is simply something everyone gets, but on my last project I was having a hell of a time getting the program to act the way I wanted to when the user click the "Exit" button or the "X" in the top-right corner. I wanted the user to be able to confirm the close. And I couldn't do it! But, today, I've realized what to do. In my first tutorial ever, I will show you, the average* home programmer (with less 1337 skillz than I**) how to control your JFrame's closing operations.

*Maybe not so average.
**Probably more 1337 than I, but in true 1337 behavior, I > j00. No offense meant. All in good fun chaps Wink


And by "Experienced Tutorial" I don't mean this is a complex thing, just that I'm not going through the basic SWING stuff, so you should check out these handy tutorials if you're getting confused.



Anyways, let's get started. First, you set up your JFrame and add components, then pack and show it, like you normally would.

Java:
JFrame frame = new JFrame("FRAME!");

~add components

frame.pack();
frame.setVisible(true);


Now, this time, we're going to set the frame's default close operation. We're setting it to do nothing on close. This means that when a user clicks that little 'X', it's does NODDA! Furthermore, it means that when we DO want to close the frame, we have to call our JFrame's dispose() method.

Java:
JFrame frame = new JFrame("FRAME!");

//Set the default close operation so the window won't close
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

~add components

frame.pack();
frame.setVisible(true);


In order to take over the window handling events, our class needs to implement the WindowListener interface. I take it you all know how to do this and what it means (why I said Experienced tutorial). To make it a bit easier, here's the methods WindowListener requires:

Java:
public void windowClosing(WindowEvent e){}
public void windowClosed(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}


All we're concerned with is the windowClosing method. This is called when that 'X' is clicked. For our frame to take advantage of this, we need to add the window listener to it. So we add in this line:

Java:
JFrame frame = new JFrame("FRAME!");

//Set the default close operation so the window won't close
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

//Add window listener
frame.addWindowListener(this);

~add components

frame.pack();
frame.setVisible(true);


Now when that 'X' is clicked, it does only what's in the windowClosing() method.

So there, now you have control. Now what can we do with it? AHA! I'm glad you asked. And I like to annoy you further Smile. Well, for one, which is what I've been doing, is asking the user to confirm their action (wouldn't it such to close accidently and loose all your progress?) So let's make an exit() method to be called when the user clicks that 'X' or an exit menu item or something of the like.

Here's a simple method:

Java:
void exit()
{
        ~ask user to confirm quit
       
        if (userConfirmed)
        {                            
                //Dispose close
                frame.dispose();
        }
}


Now we just call exit() in the windowClosing() method or anywhere else we want to confirm the user's exit.

Java:
public void windowClosing(WindowEvent e)
        {
                exit();
        }


That would do it. If the user responded yes, the frame will dispose, otherwise the frame will go on as if nothing happened.

And here's using a JOptionPane dialog to do it:

Java:
void exit()
{
        //Display confirm dialog
        int confirmed = JOptionPane.showConfirmDialog(frame,
                "Are you sure you want to quit?", "Confirm Quit",
                JOptionPane.YES_NO_OPTION);
       
        //Close if user confirmed
        if (confirmed == JOptionPane.YES_OPTION)
        {                            
                //Close frame
                frame.dispose();
        }
}


There you go. Hope at least someone can use this. Feel free to correct me if somethings wrong. Smile

Author:  rizzix [ Thu Aug 25, 2005 12:41 pm ]
Post subject: 

nice job.. ++bits.. but i might as well add in..

If you are only going to implement the public void windowClosing(WindowEvent e); method, then there's no need to implement the entire WindowListener.. instead simply extend the WindowAdapter.

so your code would look something like this (following the tutorial above..):
Java:
frame.addWindowListener(
    new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            exit();
        }
    }
);


: