|
16.2. A Simple Swing ProgramLet's take a look at a very simple (in its function, not in its composition) Swing programa simple "Hello, world" that will appear in a window (Example 16.1). Example 16.1. A simple Swing applicationimport 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
While this may look like a lot of extra junk just to say "Hello, world," remember that a GUI is not just providing output in fancy windows, but also monitoring and responding to a wide variety of user inputsa capability of which we make little or no use in this example. But you can see some of this extra capabilitygrab the lower left corner of the window frame and expand and resize the window. |
|