You create graphical user interfaces using GUI objects such as buttons, labels, text fields, check boxes, radio buttons , and combo boxes. Each type of GUI object is defined in a class, such as JButton , JLabel , JTextField , JCheckBox , JRadioButton , and JComboBox . Each GUI component class provides several constructors that you can use to create GUI component objects. The following are examples to create buttons, labels, text fields, check boxes, radio buttons, and combo boxes:
// Create a button with text OK JButton jbtOK = new JButton( "OK" ); // Create a label with text "Enter your name: " JLabel jlblName = new JLabel( "Enter your name: " ); // Create a text field with text "Type Name Here" JTextField jtfName = new JTextField( "Type Name Here" ); // Create a check box with text bold JCheckBox jchkBold = new JCheckBox( "Bold" ); // Create a radio button with text red JRadioButton jrbRed = new JRadioButton( "Red" ); // Create a combo box with choices red, green, and blue JComboBox jcboColor = new JComboBox( new String[]{ "Red" , "Green" , "Blue" });
Figure 12.1 shows these objects displayed in a frame. How to add components into a frame will be introduced in §12.4.2.
Why do the GUI component classes have the prefix J ? Instead of JButton , why not name it simply Button ? In fact, there is a class already named Button in the java.awt package.
When Java was introduced, the GUI classes were bundled in a library known as the Abstract Windows Toolkit (AWT). For every platform on which Java runs, the AWT components are automatically mapped to the platform-specific components through their respective agents , known as peers . AWT is fine for developing simple graphical user interfaces, but not for developing comprehensive GUI projects. Besides, AWT is prone to platform-specific bugs because its peer-based approach relies heavily on the underlying platform. With the release of Java 2, the AWT user-interface components were replaced by a more robust, versatile, and flexible library known as Swing components . Swing components are painted directly on canvases using Java code, except for components that are subclasses of java.awt.Window or java.awt.Panel , which must be drawn using native GUI on a specific platform. Swing components are less dependent on the target platform and use less of the native GUI resource. For this reason, Swing components that don't rely on native GUI are referred to as lightweight components , and AWT components are referred to as heavyweight components .
To distinguish new Swing component classes from their AWT counterparts, the names of Swing GUI component classes begin with a prefixed J . Although AWT components are still supported in Java 2, it is better to learn to how program using Swing components, because the AWT user-interface components will eventually fade away. This book uses Swing GUI components exclusively.