Saturday, December 24, 2011

Minimal Swing GUI example

A well behaved graphical application will place windows like other applications on the platform place them, and will exit when the last window is closed, and also all GUI work will happen on the event thread, this example does all of that.

package org.yi.happy.teaching.gui;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class SwingLaunch {
    public static void main(String[] args) {

        /* ALL GUI work should be done on the event thread */
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {

                /* make a window */
                JFrame frame = new JFrame(SwingLaunch.class.getName());
                frame.pack();

                /*
                 * when all the windows are disposed the application will exit,
                 * make the window automatically dispose when it is closed
                 */
                frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

                /* put the window where the platform would put it */
                frame.setLocationByPlatform(true);

                /* show the window on the screen */
                frame.setVisible(true);
            }
        });
    }
}

For Day Job I have also written a GUI Launcher class that takes a swing component or a class and launches a window containing it with these settings.

No comments:

Post a Comment