Java Swing: Custom Options to a JFrame’s setDefaultCloseOperation() Method

If you’re a Java Swing programmer, and you use the JFrame to make a window, you’ll probably use JFrame’s setDefaultCloseOperation() method. This just tells the JFrame what to do if the user presses the big X on the top of the window.

JFrame frame = new JFrame("Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

There are not many options when choosing the default close operation. There’s EXIT_ON_CLOSE, which closes all the windows and quits the program, there’s DO_NOTHING_ON_CLOSE, which does nothing, there’s HIDE_ON_CLOSE, which hides the window, and there’s DISPOSE_ON_CLOSE, which closes the window for good, but the Java Virtual Machine is still running.

But what if you wanted a confirmation alert to popup when the user pressed the X? Or something else? How do you give the JFrame a custom close operation to run on close? The answer is to override its dispose() method. Make a class that extends JFrame, then build your components in the constructor. Then override the dispose() method.

import javax.swing.*;

public class NewWindow extends JFrame {
    public NewWindow(){
        // Your components here
        // …

        pack();
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        NewWindow view1 = new NewWindow();
    }

    // Override the dispose method.
    @Override
    public void dispose(){
        // Custom close operation here.
    }
}

Just put whatever action you want within the dispose() method, even if you’re not disposing any window. What if you still want to just simply dispose the window sometime also, without those custom operations? Just make a new method like this:

public void close(){
    super.dispose();
}

The super.dispose(); line will call the dispose() method before it was overridden.

Advertisements

About tenny1028

I love LEGO Universe, I am EXTREMELY disappointed that it had to close down, and my LU name was TheOddWarrior
This entry was posted in Programming, Uncategorized and tagged . Bookmark the permalink.

Enter a Comment on the post...

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s