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.
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 answerHide 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, orJTreeto 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);
2081 · 5 marks
Design a simple form that takes name, password, hobbies and gender as input. [5]
2078 · 5 marks
Why do we need swing components? Explain the uses of check boxes and radio buttons in GUI programming. [5]
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]
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]
2080 · 5 marks
Write a program to create a menu named 'File' with menu items 'New', 'Save,' and 'Exit'. [5]
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 answerHide 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:
| Region | Constant |
|---|---|
| Top | BorderLayout.NORTH |
| Bottom | BorderLayout.SOUTH |
| Left | BorderLayout.WEST |
| Right | BorderLayout.EAST |
| Center | BorderLayout.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
| Concept | Description |
|---|---|
JFrame | Main window container |
JButton | Clickable button component |
ActionListener | Interface 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 |
FlowLayout | Arranges buttons in a row from left to right |
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]
2079 · 5 marks
What is grid layout? Compare grid layout with grid bag layout. [5]
Show solved answerHide 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
| Feature | Grid Layout | Grid Bag Layout |
|---|---|---|
| Cell Size | All cells are of equal size | Rows and columns can have different heights and widths |
| Component Spanning | A component occupies exactly one cell | A component can span multiple rows and/or columns |
| Flexibility | Simple and rigid layout | Sophisticated and flexible layout manager |
| Complexity | Easy to use and implement | More complex; requires GridBagConstraints object |
| Component Size | All components are resized to the same cell size | Components can have different sizes and alignments |
| Use Case | Suitable for simple, uniform grids (e.g., calculator buttons) | Suitable for complex, professional GUI forms |
| Constraints | No constraints needed | Uses 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.
2077 · 5 marks
What is the task of Layout manager? Describe about default layout manager. [5]
2076 · 5 marks
Why do we need layout management? What is GridBag layout? [5]
2075 · 5 marks
Write short notes on: a. Grid Layout b. Ragged Array [2.5+2.5]
Show solved answerHide 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.
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]
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]
Make Unit 2 stick
Practice CSC419 with flashcards & quizzes