Java GUI Programming - Swing & AWT Components

Overview of Swing and AWT GUI Frameworks

  • Packages for Java GUI Development:

    • javax.swing: Contains Swing GUI components. Swing is an extension package designed to complement and improve upon AWT.

    • java.awt: Abstract Window Toolkit (AWT) package containing earlier Java GUI components.

  • Look-and-Feel (LAF):

    • Look-and-Feel refers to the appearance of an application and the way in which the user interacts with it.

    • AWT Components (Heavyweight):

    • Tied to the GUI components of the underlying operating system/platform.

    • Relies on the local platform's windowing system to determine functionality and look-and-feel.

    • When an application using AWT components executes on different Java platforms, the GUI components display differently on each platform (platform-custom look-and-feel).

    • Swing Components (Lightweight):

    • Most Swing components are lightweight components, meaning they are written entirely in Java and are not tied to actual GUI components of the underlying platform.

    • Allows developers to specify a uniform, pluggable look-and-feel across all platforms, or use each platform's custom look-and-feel.

    • Look-and-feel can be changed dynamically during application execution to enable users to choose their preferred interface style.

    • Note: A few Swing top-level components (such as JFrame, JDialog, and JWindow) are heavyweight components because they interact directly with the desktop windowing system.

Basic Swing GUI Components


Some basic GUI components
  • Component Overview Table:

    • JLabel: Displays uneditable text and/or icons.

    • JTextField: Typically receives input from the user.

    • JButton: Triggers an event when clicked with the mouse.

    • JCheckBox: Specifies an option that can be selected or not selected.

    • JComboBox: A drop-down list of items from which the user can make a selection.

    • JList: A list of items from which the user can make a selection by clicking on any one of them; multiple elements can be selected.

    • JPanel: An area in which components can be placed and organized.

  • Method Inheritance: All methods in Swing components extend or inherit original behaviors from their AWT ancestor classes (e.g., java.awt.Component).

Class Hierarchy of GUI Components


Common superclasses of the lightweight Swing components


Full inheritance whiteboard diagram
  • Superclass Relationships:

    • java.lang.Object: Root of the Java class hierarchy.

    • java.awt.Component: Direct subclass of Object. Declares attributes and behaviors common to GUI components in both java.awt and javax.swing packages. Most GUI components extend Component directly or indirectly.

    • java.awt.Container: Direct subclass of Component.

    • Components are attached to Container objects so they can be organized and displayed on the screen.

    • Any object that is a Container can organize other Component objects.

    • Because a Container is itself a Component, Container objects can be nested inside other Container objects to construct complex hierarchical GUIs.

    • javax.swing.JComponent: Direct subclass of Container.

    • Superclass of all lightweight Swing components (which are also Container objects).

  • Heavyweight vs. Lightweight Branching:

    • Heavyweight Branch (java.awt.Container):

    • java.awt.Window -> java.awt.Frame -> javax.swing.JFrame

    • java.awt.Window -> java.awt.Dialog -> javax.swing.JDialog

    • java.awt.Window -> javax.swing.JWindow

    • Feature: Uses platform-custom Look-and-Feel (LAF).

    • Lightweight Branch (javax.swing.JComponent):

    • Subclasses include JLabel, JButton, JTextField, etc.

    • Features:

      1. Consistent Look-and-Feel across all systems.

      2. Option to use platform-custom LAF.

      3. Option to load new user-defined LAF.

Key Features of JComponent

  • Common lightweight component capabilities provided by JComponent include:

    • Pluggable Look-and-Feel: Dynamically alter appearance across platforms.

    • Shortcut Keys (Mnemonics): Provides keyboard access keys for user navigation.

    • Common Event Handling: Standardized event model across components performing shared actions.

    • Tool Tips: Brief popup descriptive text displayed when hovering over a component.

    • Accessibility Support: Assistive technologies support.

    • Internationalization and Localization: Support for multi-language and regional adaptations.

Displaying Text and Images using JFrame and JLabel

  • Top-Level Container (JFrame):

    • Most windows that contain Swing components are instances of JFrame or a subclass of JFrame.

    • JFrame is an indirect subclass of java.awt.Window.

    • Standard window features provided by JFrame:

    • Title bar at the top.

    • Minimize, maximize, and close buttons.

    • Approaches to creating a JFrame:

    • Extending JFrame (public class MyFrame extends JFrame): Allows creation of new custom methods and overriding existing methods in addition to using inherited ones.

    • Instantiating JFrame directly (JFrame frame = new JFrame()): Limits functionality strictly to available methods provided by the class.

  • Label Component (JLabel):

    • Subclass of JComponent.

    • Displays read-only text, an image (Icon), or both text and an image.

  • 5-Step Process for Implementing GUI Components (e.g., JLabel):

    1. Import: Bring necessary classes into scope (e.g., import javax.swing.JLabel;).

    2. Declare: Declare component instance variable (e.g., private JLabel label1;).

    3. Initialize / Instantiate: Create object via constructor call (e.g., label1 = new JLabel("Text");).

    4. Settings (Optional): Configure visual properties (e.g., tooltips, positioning, alignments).

    5. Add: Attach component to frame/container (e.g., add(label1);).

  • Layout Management and FlowLayout:

    • Layout managers govern the exact positioning and sizing of components within containers.

    • FlowLayout (from package java.awt):

    • Places components sequentially from left to right in the order they are added via add().

    • When horizontal space is exhausted, components wrap to the next line.

    • Automatically reflows components dynamically when container dimensions change.

    • Set using setLayout(new FlowLayout()); (method inherited from Container).

  • Polymorphism and Image Loading (Icon vs. ImageIcon):

    • Supported image formats: GIF (Graphics Interchange Format), PNG (Portable Network Graphics), and JPEG (Joint Photographic Experts Group).

    • Interface Icon (package javax.swing) is implemented by ImageIcon (package javax.swing).

    • Image location retrieval: java Icon bug = new ImageIcon(getClass().getResource("bug1.png"));     

    • getClass(): Inherited indirectly from Object, retrieves the Class object representing the declaring class (LabelFrame).

    • getResource("bug1.png"): Method on Class using its class loader to obtain the resource's disk URL.

    • ImageIcon(URL): Constructor that loads the image at the given URL into memory.

    • Polymorphic Assignment Concept:

    • Instantiating a subtype to a supertype interface reference: Icon icn = new ImageIcon(...) is conceptually equivalent to inheritance setups like Person p1 = new Student(), where Person defines general fields (name, address) and Student adds specifics (id, GPA).

Positioning Constants in SwingConstants


Positioning constants
  • SwingConstants Interface Constants:

    • Interface javax.swing.SwingConstants defines integer constants for horizontal and vertical positioning.

    • Horizontal Position Constants:

    • SwingConstants.LEFT: Places text on the left.

    • SwingConstants.CENTER: Places text in the center horizontally.

    • SwingConstants.RIGHT: Places text on the right.

    • Vertical Position Constants:

    • SwingConstants.TOP: Places text at the top.

    • SwingConstants.CENTER: Places text in the center vertically.

    • SwingConstants.BOTTOM: Places text at the bottom.

    • Default Alignment Behavior: By default, in a label containing both text and an image, text appears to the right of the image, centered vertically.

Detailed Code Example: LabelFrame and LabelTest

LabelFrame.java Implementation

```java // Fig. 14.6: LabelFrame.java // Demonstrating the JLabel class. import java.awt.FlowLayout; // specifies how components are arranged import javax.swing.JFrame; // provides basic window features import javax.swing.JLabel; // displays text and images import javax.swing.SwingConstants; // common constants used with Swing import javax.swing.Icon; // interface used to manipulate images import javax.swing.ImageIcon; // loads images

public class LabelFrame extends JFrame { private JLabel label1; // JLabel with just text private JLabel label2; // JLabel constructed with text and icon private JLabel label3; // JLabel with added text and icon

// LabelFrame constructor adds JLabels to JFrame public LabelFrame() { super( "Testing JLabel" ); setLayout( new FlowLayout() ); // set frame layout

  // JLabel constructor with a string argument
  label1 = new JLabel( "Label with text" );
  label1.setToolTipText( "This is label1" );
  add( label1 ); // add label1 to JFrame

  // JLabel constructor with string, Icon and alignment arguments
  Icon bug = new ImageIcon( getClass().getResource( "bug1.png" ) );
  label2 = new JLabel( "Label with text and icon", bug, SwingConstants.LEFT );
  label2.setToolTipText( "This is label2" );
  add( label2 ); // add label2 to JFrame

  label3 = new JLabel(); // JLabel constructor no arguments
  label3.setText( "Label with icon and text at bottom" );
  label3.setIcon( bug ); // add icon to JLabel
  label3.setHorizontalTextPosition( SwingConstants.CENTER );
  label3.setVerticalTextPosition( SwingConstants.BOTTOM );
  label3.setToolTipText( "This is label3" );
  add( label3 ); // add label3 to JFrame

} // end LabelFrame constructor } // end class LabelFrame

### `LabelTest.java` Implementation

java // Fig. 14.7: LabelTest.java // Testing LabelFrame. import javax.swing.JFrame;

public class LabelTest { public static void main( String[] args ) { LabelFrame labelFrame = new LabelFrame(); // create LabelFrame labelFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); labelFrame.setSize( 260, 180 ); // set frame size labelFrame.setVisible( true ); // display frame } // end main } // end class LabelTest ```

Execution Output and GUI Display


Test class output for LabelFrame
  • Window Configuration Methods:

    • setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Ensures the application terminates when the user clicks the window's close button. By default, window closing is set to hide the window without exiting (HIDE_ON_CLOSE).

    • setSize(260, 180): Sets width to 260260 pixels and height to 180180 pixels.

    • setVisible(true): Makes the window visible on the display screen.

Best Practices, Common Errors, and Observations

  • Common Programming Error 14.1:

    • If you do not explicitly add a GUI component to a container (via add()), the GUI component will not be displayed when the container appears on the screen.

  • Look-and-Feel Observation 14.5:

    • Swing GUI components allow specifying a uniform look-and-feel across all operating systems or using each platform's native custom look-and-feel. Applications can dynamically change the look-and-feel during execution.

  • Look-and-Feel Observation 14.7:

    • Use tool tips (setToolTipText) to provide helpful descriptive text for GUI components, assisting users in understanding each component's functional purpose.