Java Tutorial: Introduction to Swing

, , 2007-12

For the next few weeks, we take a excursion into Java's GUI.

We will base our explorations from the Official Java's Tutorial: http://java.sun.com/docs/books/tutorial/uiswing/index.html

If you are not familiar with Java's GUI outlook, take a look at this Wikipedia article: Swing (Java).

And for a explanation of the general concept in GUI application programing, see: Intro to Event in GUI Programing.

Ok, let's start sans further ado. The following is a most simple GUI application. It just shows a text. Compile it, and run it. You'll see a application with a text in it, and that's all.

import javax.swing.*;        

public class gui1 {

    /**
       Create the GUI and show it. For thread safety, this method
       should be invoked from the event-dispatching thread.
    */

    private static void createAndShowGUI() {

        JFrame.setDefaultLookAndFeelDecorated(true);

        //Create and set up the window.
        JFrame myFrame = new JFrame("★ A Etude of GUI ★");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel myLabel = new JLabel("I ♥ U");
        myFrame.getContentPane().add(myLabel);

        //Display the window.
        myFrame.pack();
        myFrame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {createAndShowGUI(); }
        });
    }
}

Java Doc: JFrame

Java Doc: JLabel

The above code is based on code from: http://java.sun.com/docs/books/tutorial/uiswing/components/index.html

blog comments powered by Disqus