2 User Interface Components With Swing

Advanced Java Programming · Unit 2 · 10 hrs

User Interface Components with Swing

Exam-focused notes for User Interface Components with Swing (Advanced Java Programming, CSC419): what the TU syllabus asks and how it has actually been tested, with 14 solved past questions from this unit.

User Interface Components with Swing in short

This unit builds desktop graphical interfaces in Java, moving from the older AWT toolkit to Swing, then through the layout managers that position components and the individual controls, menus, and dialogs a Swing application is assembled from.

User Interface Components with Swing: notes

Introduction: Concept of AWT, AWT vs Swing, Java Applets, Applet Life Cycle, Swing Class Hierarchy, Component and Containers

AWT (Abstract Windowing Toolkit) is Java's original API for building GUI applications. AWT components are heavyweight and platform-dependent: each AWT component delegates to the underlying operating system to draw itself (a text box in AWT is really the operating system's own text box), so the same AWT application looks like a native Windows application on Windows and a native macOS application on macOS.

Swing, part of the Java Foundation Classes (JFC), was built on top of AWT to fix these limitations. Swing components are lightweight (drawn entirely by Java itself rather than delegated to the OS), platform independent in appearance, support pluggable look and feel, follow the Model-View-Controller (MVC) pattern, and offer a much richer component set (tables, trees, scroll panes) than AWT does.

AWTSwing
Platform dependentPlatform independent
Heavyweight componentsLightweight components
No pluggable look and feelPluggable look and feel
Does not follow MVCFollows MVC
Fewer, simpler componentsRicher component set (tables, trees, lists, and more)

Java applets are small Java programs that run inside a web page, transported over the network and executed by the browser's JVM (or a standalone applet viewer). Every applet is a subclass of java.applet.Applet and, unlike a standalone application, has no main method; the browser's plugin drives it directly.

import java.awt.*;
import java.applet.*;

public class Simple extends Applet {
    public void paint(Graphics g) {
        g.drawString("A simple Applet", 20, 20);
    }
}

The applet life cycle consists of four methods that the browser calls automatically: init(), called once when the applet is first loaded, used to perform one-time initialization; start(), called after init() and again every time the applet becomes visible after being stopped; stop(), called to suspend background activity (such as an animation thread) while the applet is not visible; and destroy(), called once to release resources when the applet is being removed from memory entirely.

The Swing class hierarchy descends from Object through Component and Container. Component is an abstract class encapsulating everything common to any drawable, interactive element: its current size and position, foreground and background colors, font, and its role in generating and receiving events. Container is a subclass of Component that can hold other components (and other containers), which is what makes nested, multi-level GUIs possible; Window, Panel, and Applet all descend from Container, and Swing's own JComponent (the base of JButton, JLabel, JTextField, and the rest) descends from Container as well. A Container positions whatever is added to it using a layout manager, which can be replaced with setLayout().

What this unit covers

  • Introduction: Concept of AWT, AWT vs Swing, Java Applets, Applet Life Cycle, Swing Class Hierarchy, Component and Containers
  • Layout Management: No Layout, Flow layout, Border Layout, Grid Layout, Gridbag Layout, Group Layout
  • GUI Controls: Text Fields, Password Fields, Text Areas, Scroll Pane, Labels, Check Boxes, Radio Buttons, Borders, Combo Boxes, Sliders
  • Menu, Menu Item, Icons in Menu Items, Check Box and Radio Buttons in Menu Items, Pop-up Menus, Keyboard Mnemonics and Accelerators, Enabling and Disabling Menu Items, Toolbars, Tooltips
  • Option Dialogs, Creating Dialogs, File Choosers, Color Choosers, Internal Frames, Frames, Tables, Trees, and Tables

GUI Controls

2081 · 10 marks

What are the tasks of sliders and scroll pane? Explain any four types of layout manager.[10]

Show solved answer

Tasks of Sliders and Scroll Pane, and Four Types of Layout Manager


Part 1: Tasks of Sliders and Scroll Pane

Sliders

A Slider is a GUI component that allows the user to select a numeric value by sliding a knob (thumb) along a track between a defined minimum and maximum value.

Tasks of Sliders:

  • Allow the user to select a value from a continuous or discrete range of values (e.g., volume control, brightness control).
  • Display the current value visually through the position of the knob on the track.
  • Support both horizontal and vertical orientations.
  • Can display tick marks and tick labels to indicate specific values along the track.
  • Fire ChangeEvent whenever the slider value changes, allowing the program to respond to user interaction.
  • Can be set with a minimum, maximum, and initial (default) value.
  • Support snap-to-ticks feature so the knob snaps to the nearest tick mark.

Example:

JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 50);
slider.setMajorTickSpacing(10);
slider.setPaintTicks(true);
slider.setPaintLabels(true);

Scroll Pane:

"ScrollPane is used to make a scrollable view of a component. When screen size is limited, we use a scroll pane to display a large component."

Tasks of Scroll Pane:

  • Provide a scrollable view of a component that is too large to fit in the available screen area.
  • Automatically display horizontal and/or vertical scroll bars when the content exceeds the visible area.
  • Allow the user to scroll through large content such as large images, long text areas, or large tables.
  • Manage the viewport (the visible portion of the component at any given time).
  • Can be configured to show scroll bars always, never, or only when needed.
  • Wrap components like JTextArea, JTable, JList, or JTree to make them scrollable.

Example:

JTextArea textArea = new JTextArea(5, 30);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

Part 2: Four Types of Layout Manager

A Layout Manager in Java is an object that controls the size and position of components within a container. Java provides several built-in layout managers.


1. FlowLayout

FlowLayout is the default layout manager for JPanel. It arranges components in a left-to-right flow, much like lines of text in a paragraph. When one row is filled, it starts a new row.

Key Features:

  • Components are placed in a row from left to right.
  • When the row is full, components wrap to the next row.
  • Alignment can be set to LEFT, RIGHT, or CENTER (default is CENTER).
  • Gaps between components can be specified (horizontal and vertical gaps).

Example:

JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));

Diagram:

[ Button1 ] [ Button2 ] [ Button3 ]
[ Button4 ] [ Button5 ]

2. BorderLayout

BorderLayout is the default layout manager for JFrame and JDialog. It divides the container into five regions: North, South, East, West, and Center.

Key Features:

  • Each region can hold only one component.
  • The Center region expands to fill all remaining space.
  • North and South regions stretch horizontally.
  • East and West regions stretch vertically.
  • If a region is not used, the Center expands to fill that space.

Example:

JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(new JButton("North"),  BorderLayout.NORTH);
frame.add(new JButton("South"),  BorderLayout.SOUTH);
frame.add(new JButton("East"),   BorderLayout.EAST);
frame.add(new JButton("West"),   BorderLayout.WEST);
frame.add(new JButton("Center"), BorderLayout.CENTER);

Diagram:

+---------------------------+
|          NORTH            |
+------+------------+-------+
| WEST |   CENTER   | EAST  |
+------+------------+-------+
|          SOUTH            |
+---------------------------+

3. GridLayout

GridLayout arranges components in a rectangular grid of rows and columns. Every cell in the grid is of equal size, and each component fills its cell completely.

Key Features:

  • Components are placed row by row, left to right, top to bottom.
  • All cells have the same width and height.
  • The number of rows and columns is specified at creation.
  • Horizontal and vertical gaps between cells can be set.

Example:

JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2, 5, 5)); // 3 rows, 2 cols
panel.add(new JButton("1"));
panel.add(new JButton("2"));
panel.add(new JButton("3"));
panel.add(new JButton("4"));
panel.add(new JButton("5"));
panel.add(new JButton("6"));

Diagram:

+--------+--------+
|   1    |   2    |
+--------+--------+
|   3    |   4    |
+--------+--------+
|   5    |   6    |
+--------+--------+

4. GridBagLayout:

"GridBagLayout is a sophisticated, flexible layout manager that aligns components vertically, horizontally, or along their baseline, without requiring that the components be of the same size."

Key Features:

  • Components are placed on a grid of rows and columns, but unlike GridLayout, cells can span multiple rows/columns and can be of different sizes.
  • Each component's placement and sizing is controlled by a GridBagConstraints object (gridx, gridy, gridwidth, gridheight, weightx, weighty, fill, anchor, insets).
  • It is the most flexible but also the most complex layout manager in the AWT/Swing family.

Example:

JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();

gbc.gridx = 0; gbc.gridy = 0;
panel.add(new JButton("Button 1"), gbc);

gbc.gridx = 1; gbc.gridy = 0;
panel.add(new JButton("Button 2"), gbc);
Open this answer on its own page →

2081 · 5 marks

Design a simple form that takes name, password, hobbies and gender as input. [5]

The form below collects name, password, hobbies (multiple values using checkboxes), and gender (using radio buttons). Since password is sensitive data, the POST method is used. --- --- Field Input Type Servlet Method Used Reason --------------------------------------------------------------------...

Open this answer on its own page →

2078 · 5 marks

Why do we need swing components? Explain the uses of check boxes and radio buttons in GUI programming. [5]

--- Java Swing is part of the Java Foundation Classes (JFC) used to create window-based (GUI) applications. It is built on top of AWT (Abstract Windowing Toolkit) and is entirely written in Java. We need Swing components because of the following advantages over AWT: Feature AWT Swing --------- Pl...

Open this answer on its own page →

2075 · 10 marks

Design a GUI form using swing with a text field, a text label for displaying the input message 'Input any String', and three buttons with caption CheckPalindrome, Reverse, FindVowels. Write a complete program for above scenario and for checking palindrome in first button, reverse it after clicking second button and extract the vowels from it after clicking third button.[10]

--- Input String Button Clicked Output Displayed --------- madam CheckPalindrome "madam" is a Palindrome hello CheckPalindrome "hello" is NOT a Palindrome hello Reverse Reversed String: olleh hello FindVowels Vowels in "hello": e o (Count = 2) --- - Extends JFrame to create a window - Implements ...

Open this answer on its own page →

Menu, Menu Item, Icons in Menu Items, Check Box and Radio Buttons in Menu Items, Pop-up Menus, Keyboard Mnemonics and Accelerators, Enabling and Disabling Menu Items, Toolbars, Tooltips

2081 · 5 marks

How do you insert pop-up menu? Distinguish between GET and POST request. [5]

--- In Java AWT, the Choice class is used to create a pop-up menu (combo box). The object of the Choice class shows a pop-up menu of choices, and the choice selected by the user is shown on the top of the menu. 1. Create a Choice object 2. Add items using add() method 3. Add the Choice object to ...

Open this answer on its own page →

2080 · 5 marks

Write a program to create a menu named 'File' with menu items 'New', 'Save,' and 'Exit'. [5]

In Java Swing, menus are created using: - JMenuBar - the menu bar that holds menus - JMenu - a single menu (e.g., "File") - JMenuItem - individual items inside a menu (e.g., "New", "Save", "Exit") - ActionListener - to handle click events on menu items --- --- Action Performed Console Output ----...

Open this answer on its own page →

Layout Management

2080 · 10 marks

Describe any two types of Layout manager. Using swing components, design a form with three buttons with captions 'RED,' 'BLUE,' and 'GREEN,' respectively. Then write a program to handle the event such that when the user clicks the button, the color of that button will be the same as its caption.[10]

Show solved answer

Layout Managers and Swing Event Handling

Part 1: Two Types of Layout Managers

1. FlowLayout

FlowLayout is the default layout manager for JPanel. It arranges components in a left-to-right flow, much like lines of text in a paragraph. When one row is filled, it starts a new row.

Key features:

  • Components are placed in a row from left to right
  • When the row is full, a new row begins
  • Components retain their preferred size
  • Alignment can be set to LEFT, RIGHT, or CENTER (default is CENTER)

Example:

setLayout(new FlowLayout());

2. BorderLayout

BorderLayout is the default layout manager for JFrame. It divides the container into five regions:

RegionConstant
TopBorderLayout.NORTH
BottomBorderLayout.SOUTH
LeftBorderLayout.WEST
RightBorderLayout.EAST
CenterBorderLayout.CENTER

Key features:

  • Only one component can be placed in each region
  • The CENTER region takes up all remaining space
  • NORTH and SOUTH stretch horizontally
  • EAST and WEST stretch vertically

Example:

setLayout(new BorderLayout());
add(button, BorderLayout.NORTH);

Part 2: Swing Program - Button Color Change on Click

Program Description

When the user clicks the RED, BLUE, or GREEN button, the background color of that button changes to match its caption color.


Complete Java Program

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ColorButtons extends JFrame implements ActionListener {

    // Declare three buttons
    JButton b1, b2, b3;

    // Constructor
    ColorButtons() {
        // Set title of the window
        setTitle("Color Button Demo");

        // Set layout manager
        setLayout(new FlowLayout());

        // Initialize buttons with captions
        b1 = new JButton("RED");
        b2 = new JButton("BLUE");
        b3 = new JButton("GREEN");

        // Add action listeners to each button
        b1.addActionListener(this);
        b2.addActionListener(this);
        b3.addActionListener(this);

        // Add buttons to the frame
        add(b1);
        add(b2);
        add(b3);

        // Frame settings
        setSize(400, 150);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    // Event handling method
    @Override
    public void actionPerformed(ActionEvent e) {

        // Check which button was clicked and change its background color
        if (e.getSource() == b1) {
            b1.setBackground(Color.RED);
        }
        else if (e.getSource() == b2) {
            b2.setBackground(Color.BLUE);
        }
        else if (e.getSource() == b3) {
            b3.setBackground(Color.GREEN);
        }
    }

    // Main method
    public static void main(String[] args) {
        new ColorButtons();
    }
}

Output / Form Design

+------------------------------------------+
|        Color Button Demo                 |
+------------------------------------------+
|                                          |
|   [ RED ]     [ BLUE ]     [ GREEN ]     |
|                                          |
+------------------------------------------+
  • Clicking RED button --> button background turns Red
  • Clicking BLUE button --> button background turns Blue
  • Clicking GREEN button --> button background turns Green

Key Points Explained

ConceptDescription
JFrameMain window container
JButtonClickable button component
ActionListenerInterface to handle button click events
actionPerformed()Method called automatically when a button is clicked
e.getSource()Returns the object (button) that triggered the event
setBackground(Color.RED)Sets the background color of the button
FlowLayoutArranges buttons in a row from left to right
Open this answer on its own page →

2079 · 10 marks

Why do we need layout management? Explain any two layout managers with example. Write a simple GUI program that displays 'Hello World' in a text field. The program should display output if user clicks a button.[10]

Layout management is needed to automatically arrange and position GUI components (buttons, text fields, labels, etc.) within a container (like JFrame or JPanel). Without a layout manager, we would have to manually specify the exact pixel coordinates of every component, which causes the following ...

Open this answer on its own page →

2079 · 5 marks

What is grid layout? Compare grid layout with grid bag layout. [5]

Show solved answer

Grid Layout and Comparison with Grid Bag Layout

Grid Layout

Grid Layout is a layout manager in Java that arranges components in a rectangular grid of rows and columns. Every cell in the grid has the same size, and each component is placed in one cell, filling the entire cell. Components are added to the grid from left to right, top to bottom.

Key characteristics of Grid Layout:

  • Divides the container into equal-sized cells
  • Each cell holds exactly one component
  • All rows have the same height and all columns have the same width
  • Components are resized to fill their cell

Syntax:

setLayout(new GridLayout(rows, cols));
// or with gaps:
setLayout(new GridLayout(rows, cols, hgap, vgap));

Example:

JFrame frame = new JFrame();
frame.setLayout(new GridLayout(2, 3)); // 2 rows, 3 columns
frame.add(new JButton("1"));
frame.add(new JButton("2"));
frame.add(new JButton("3"));
frame.setSize(300, 200);
frame.setVisible(true);

Comparison: Grid Layout vs Grid Bag Layout

FeatureGrid LayoutGrid Bag Layout
Cell SizeAll cells are of equal sizeRows and columns can have different heights and widths
Component SpanningA component occupies exactly one cellA component can span multiple rows and/or columns
FlexibilitySimple and rigid layoutSophisticated and flexible layout manager
ComplexityEasy to use and implementMore complex; requires GridBagConstraints object
Component SizeAll components are resized to the same cell sizeComponents can have different sizes and alignments
Use CaseSuitable for simple, uniform grids (e.g., calculator buttons)Suitable for complex, professional GUI forms
ConstraintsNo constraints neededUses GridBagConstraints to control placement

Note (from notes): GridBagLayout is described as "a sophisticated, flexible layout manager that aligns components to span more than one cell. The rows in the grid can have different heights, and grid columns can have different widths." This is the key advantage over the simpler Grid Layout.


Summary

Grid Layout is best used when all components should be the same size in a uniform grid. Grid Bag Layout is preferred when the GUI requires components of varying sizes, spanning multiple cells, making it more powerful but also more complex to configure.

Open this answer on its own page →

2077 · 5 marks

What is the task of Layout manager? Describe about default layout manager. [5]

A Layout Manager is responsible for controlling the size and position (arrangement) of components placed inside a container. The main tasks of a layout manager are: - Positioning components within a container automatically - Determining the size of each component based on available space - Arrang...

Open this answer on its own page →

2076 · 5 marks

Why do we need layout management? What is GridBag layout? [5]

In Java, when we build a GUI application, we place multiple components (buttons, labels, text fields, etc.) inside a container (like a Frame or Panel). Layout management is needed for the following reasons: 1. Platform Independence: Java runs on different operating systems (Windows, Linux, Mac) w...

Open this answer on its own page →

2075 · 5 marks

Write short notes on: a. Grid Layout b. Ragged Array [2.5+2.5]

Show solved answer

Short Notes


a. Grid Layout

GridPane (Grid Layout in JavaFX) is a layout manager that arranges nodes in a flexible grid of rows and columns. It allows multiple nodes to be placed in multiple rows and columns within a single container.

Key Features:

  • Nodes can be placed in any cell of the grid by specifying the column index and row index.
  • The grid is flexible -- rows can have different heights and columns can have different widths.
  • A more advanced form, GridBagLayout, is a sophisticated and flexible layout manager that allows components to span more than one cell.
  • It is useful for creating form-like interfaces where labels and input fields are aligned in rows and columns.

Example Usage (JavaFX GridPane):

GridPane grid = new GridPane();
grid.add(new Label("Name:"), 0, 0);   // column 0, row 0
grid.add(new TextField(), 1, 0);      // column 1, row 0
grid.add(new Label("Email:"), 0, 1);  // column 0, row 1
grid.add(new TextField(), 1, 1);      // column 1, row 1

This creates a structured, tabular arrangement of UI components.


b. Ragged Array

A ragged array (also called a jagged array) is a multidimensional array in Java where each row can have a different number of columns. Unlike a regular 2D array where all rows have the same length, a ragged array allows rows of varying sizes.

Key Features:

  • In Java, a 2D array is essentially an array of arrays, so each row can be independently sized.
  • This saves memory when rows do not need equal lengths.
  • Each row is a separate one-dimensional array object.

Declaration and Initialization:

int[][] ragged = new int[3][];   // 3 rows, columns not yet defined

ragged[0] = new int[2];          // row 0 has 2 columns
ragged[1] = new int[4];          // row 1 has 4 columns
ragged[2] = new int[3];          // row 2 has 3 columns

Visual Representation:

Row 0:  [ ][ ]
Row 1:  [ ][ ][ ][ ]
Row 2:  [ ][ ][ ]

Example with values:

int[][] ragged = {
    {1, 2},
    {3, 4, 5, 6},
    {7, 8, 9}
};

Ragged arrays are particularly useful in applications like triangular matrices or storing data of unequal lengths, where allocating equal-sized rows would waste memory.

Open this answer on its own page →

Option Dialogs, Creating Dialogs, File Choosers, Color Choosers, Internal Frames, Frames, Tables, Trees, and Tables

2080 · 5 marks

When do we need an internal frame? How do you create a table using Swing? [5]

An Internal Frame (JInternalFrame) is needed in the following situations: - When we want to create a Multiple Document Interface (MDI) application, where several windows (documents) exist inside a single main window. - When we need a lightweight frame-like container inside a parent frame that pro...

Open this answer on its own page →

Introduction

2078 · 10 marks

Compare AWT with Swing. Write a GUI program using components to find sum and difference of two numbers. Use two text fields for giving input and a label for output. The program should display sum if user presses mouse and difference if user release mouse.[10]

--- Feature AWT (Abstract Window Toolkit) Swing --------- Package java.awt javax.swing Components Heavyweight (depend on OS native components) Lightweight (drawn by Java itself, not OS) Look and Feel Platform dependent (looks different on each OS) Platform independent (consistent look on all OS) ...

Open this answer on its own page →