Java Reference
In-Depth Information
16.2
A S IMPLE S WING P ROGRAM
Let's take a look at a very simple (in its function, not in its composition)
Swing program—a simple “Hello, world” that will appear in a window
(Example 16.1).
Example 16.1 A simple Swing application
import java.awt.*;
import javax.swing.*;
public class
hw
{
public static void
main(String[] args)
{
//Create the top-level container
JFrame frame = new JFrame();
JLabel hi = new JLabel("Hello, world.");
frame.getContentPane().add(hi, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack(); // kicks the UI into action
frame.setVisible(true);
} // main
} // class hw
Now compile this program and run it from the command line like this:
$ javac hw.java
$ java hw
You should then see a small window appear, looking as in Figure 16.1.
Figure 16.1 “Hello, world” in a Swing window
Search WWH ::




Custom Search