Advanced Java Programming · Unit 3
GUI Programming with AWT and Swing
Exam-focused notes for GUI Programming with AWT and Swing (Advanced Java Programming, BIT401): what the TU syllabus asks and how it has actually been tested, with 11 solved past questions from this unit.
GUI Programming with AWT and Swing in short
Java builds desktop windows with AWT and Swing. This chapter explains components, layouts, events, menus and the mouse and keyboard.
What this unit covers
- Components and containers
- Layout managers: flow layout, grid layout, border layout
- Event handling and action commands
- Button and label widgets
- Text boxes and text fields
- Menu items with mnemonics and accelerators
- Mouse events and keyboard events
- JPanel usage and customization
Layout managers
2082 · 10 marks
Distinguish between component and containers. What do you mean by keyboard mnemonics and accelerators? Illustrate the concept of Grid layout with an example.[10]
Show solved answerHide answer
Model Answer: Components, Containers, Mnemonics, Accelerators, and Grid Layout
1. Components vs Containers
Components:
- Basic building blocks of GUI applications
- Lightweight objects that represent visual elements
- Examples: JButton, JLabel, JTextField, JCheckBox, JRadioButton
- Cannot contain other components
- Directly display information or accept user input
- Have their own appearance and behavior
Containers:
- Special components that can hold other components
- Used to organize and manage groups of components
- Examples: JFrame, JPanel, JDialog, JWindow
- Provide layout management for contained components
- Inherit from Component class but add containment capability
- Manage the positioning and sizing of child components
Key Distinction: Containers are components that can contain other components, whereas components are atomic UI elements that cannot contain other components.
2. Keyboard Mnemonics and Accelerators
Keyboard Mnemonics:
- Single character shortcuts that activate a button or menu item
- Accessed by pressing Alt + the mnemonic key
- Underlined character in the button/menu label
- Example: In a button labeled "Save", 'S' is the mnemonic
- User presses Alt+S to activate the button
- Provides keyboard navigation for accessibility
Accelerators:
- Keyboard shortcuts that directly invoke an action without focus requirement
- Typically use Ctrl key combined with another key
- Example: Ctrl+S for Save, Ctrl+C for Copy
- Work globally regardless of which component has focus
- Faster than mnemonics for experienced users
- Commonly used in menu items
Difference: Mnemonics require Alt key and component focus; accelerators work globally with Ctrl (or other modifier) combinations.
3. Grid Layout with Example
Grid Layout Concept:
- Arranges components in a rectangular grid of rows and columns
- All components are given equal size
- Components fill the grid cells uniformly
- Useful for creating uniform button arrays or form layouts
Constructor:
GridLayout(int rows, int columns)
GridLayout(int rows, int columns, int hgap, int vgap)
Where hgap and vgap are horizontal and vertical gaps between components.
Example Code:
import javax.swing.*;
import java.awt.*;
public class GridLayoutExample extends JFrame {
public GridLayoutExample() {
setTitle("Grid Layout Demo");
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create panel with GridLayout (3 rows, 3 columns)
JPanel panel = new JPanel(new GridLayout(3, 3, 5, 5));
// Add 9 buttons
for (int i = 1; i <= 9; i++) {
JButton btn = new JButton("Button " + i);
panel.add(btn);
}
add(panel);
setVisible(true);
}
public static void main(String[] args) {
new GridLayoutExample();
}
}
Output: Creates a 3x3 grid of 9 equal-sized buttons with 5-pixel gaps between them.
Total Answer Length: Appropriate for 10 marks with clear distinctions, definitions, and practical example.
2080 · 5 marks
What is layout manager? Explain working of flow layout with example. [5]
Show solved answerHide answer
Layout Manager - Model Answer
What is Layout Manager?
A layout manager is a component in Java GUI programming that automatically arranges and positions components (like buttons, labels, text fields) within a container. It controls the size and position of components based on predefined rules, eliminating the need for manual positioning.
Key purposes:
- Automatically manages component placement
- Handles resizing when window is resized
- Ensures consistent appearance across different screen resolutions
- Reduces manual coordinate calculations
Flow Layout - Working and Explanation
How Flow Layout Works:
Flow Layout is the default layout manager for JPanel. It arranges components in a left-to-right, top-to-bottom manner, similar to text flow in a document.
Characteristics:
- Components are placed horizontally from left to right
- When a row is full, components wrap to the next row
- Each component takes its preferred size
- Components are centered by default within the container
- Respects gaps between components (horizontal and vertical)
Example:
import javax.swing.*;
public class FlowLayoutExample extends JFrame {
public FlowLayoutExample() {
setTitle("Flow Layout Demo");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create panel with FlowLayout
JPanel panel = new JPanel(new FlowLayout());
// Add components
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));
panel.add(new JButton("Button 4"));
panel.add(new JButton("Button 5"));
add(panel);
setVisible(true);
}
public static void main(String[] args) {
new FlowLayoutExample();
}
}
Output behavior:
- Buttons 1, 2, 3, 4 appear in first row (left to right)
- Button 5 wraps to second row
- When window is resized, components reflow automatically
Note: Standard Java Swing documentation used for layout manager concepts as reference notes were unavailable.
Text boxes and text fields
2082 · 5 marks
Design a form that contains two text fields and two buttons with caption 'OK' and 'CANCEL' using AWT. [5]
Show solved answerHide answer
Model Answer: AWT Form with Text Fields and Buttons
Program Code:
import java.awt.*;
import java.awt.event.*;
public class SimpleForm extends Frame {
// Declare components
TextField textField1, textField2;
Button okButton, cancelButton;
// Constructor
public SimpleForm() {
// Set frame properties
setTitle("Simple Form");
setSize(300, 200);
setLayout(new FlowLayout());
// Create and add labels
add(new Label("Field 1:"));
// Create first text field
textField1 = new TextField(20);
add(textField1);
add(new Label("Field 2:"));
// Create second text field
textField2 = new TextField(20);
add(textField2);
// Create OK button
okButton = new Button("OK");
add(okButton);
// Create CANCEL button
cancelButton = new Button("CANCEL");
add(cancelButton);
// Add event listeners
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Field 1: " + textField1.getText());
System.out.println("Field 2: " + textField2.getText());
}
});
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// Handle window close
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setVisible(true);
}
// Main method
public static void main(String[] args) {
new SimpleForm();
}
}
Key Components Explained:
| Component | Purpose |
|---|---|
| Frame | Container window for the form |
| TextField | Input fields for user data (2 fields) |
| Button | Clickable buttons with captions 'OK' and 'CANCEL' |
| FlowLayout | Arranges components in a row |
| ActionListener | Handles button click events |
Output:
- Form displays with two text input fields
- Two buttons labeled "OK" and "CANCEL"
- OK button prints field values to console
- CANCEL button closes the application
2080 · 10 marks
Write a Java program to create a UI with three labels and three text boxes for First Number, Second Number and Result. Also put Four buttons (Add, Subtract, Multiply, and Divide) in the form and handle the event accordingly.[10]
0 · 10 marks
Write a java program to create a UI with four labels and three text boxes for Principal, Time, Rate, and Interest. Also put two buttons "Simple Interest" and Reset in the form and handle the event accordingly.[10]
Mouse events and keyboard events
2082 · 5 marks
Write a program to illustrate the concept of Mouse Events. [5]
Menu items with mnemonics and accelerators
2081 · 10 marks
When do we use JPanel? How do you add mnemonics and accelerators to menu items? Explain.[10]
Event handling and action commands
2081 · 5 marks
Write a program to design a form with a button and label, such that the number of times the button is clicked will be displayed in label. [5]
0 · 5 marks
What is action command? How it is used in java programs? Explain with example. [5]
Make Unit 3 stick
Practice BIT401 with flashcards & quizzes