3 Gui Programming With Awt And Swing

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.

GUI Programming with AWT and Swing: notes

Components and containers

A component is a visible item the user sees or uses, such as a button, label or text box. A container is a component that holds other components, such as a frame or panel. Every container is a component, but not every component is a container.

ComponentContainer
A single GUI itemHolds many components
Examples: JButton, JLabelExamples: JFrame, JPanel
Cannot add other itemsHas the add() method

AWT (java.awt) uses the native widgets of the operating system, so it is heavyweight. Swing (javax.swing) draws its own widgets in Java, so it is lightweight and looks the same everywhere. Swing class names start with J.

import javax.swing.*;

public class FrameDemo {
    public static void main(String[] args) {
        JFrame f = new JFrame("My Window");
        f.setSize(300, 200);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new JLabel("Hello Swing"));
        f.setVisible(true);
    }
}

Layout managers: flow layout, grid layout, border layout

A layout manager decides the size and position of components in a container. We set one with setLayout().

  • FlowLayout puts components in a row, left to right, and wraps to a new row when full. It is the default for JPanel.
  • GridLayout divides the container into equal cells in rows and columns. Each component fills one cell.
  • BorderLayout has five regions: North, South, East, West and Center. It is the default for the JFrame content pane. Extra space goes to the Center.
import javax.swing.*;
import java.awt.*;

public class LayoutDemo {
    public static void main(String[] args) {
        JFrame f = new JFrame("Grid");
        f.setLayout(new GridLayout(2, 3, 5, 5));
        for (int i = 1; i <= 6; i++) f.add(new JButton("Btn " + i));
        f.setSize(300, 150);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

The numbers are rows, columns, horizontal gap and vertical gap. For FlowLayout use new FlowLayout(FlowLayout.LEFT, 10, 10). For BorderLayout use f.add(comp, BorderLayout.NORTH).

Event handling and action commands

Swing uses the delegation event model. An event source (a button) creates an event object. A listener registered on it receives the event and runs a handler method. For a button click, the listener is ActionListener with actionPerformed(ActionEvent e).

An action command is a string linked to an event. Set it with setActionCommand("save") and read it with e.getActionCommand(). One listener can then serve many buttons. By default a button's command is its caption.

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

public class ClickCounter {
    public static void main(String[] args) {
        JFrame f = new JFrame("Counter");
        JButton b = new JButton("Click");
        JLabel l = new JLabel("Clicks: 0");
        b.setActionCommand("count");
        int[] n = {0};
        b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (e.getActionCommand().equals("count")) {
                    n[0]++;
                    l.setText("Clicks: " + n[0]);
                }
            }
        });
        f.setLayout(new java.awt.FlowLayout());
        f.add(b); f.add(l);
        f.setSize(250, 120);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

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 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.

Open this answer on its own page →

2080 · 5 marks

What is layout manager? Explain working of flow layout with example. [5]

Show solved 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:

  1. Components are placed horizontally from left to right
  2. When a row is full, components wrap to the next row
  3. Each component takes its preferred size
  4. Components are centered by default within the container
  5. 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.

Open this answer on its own page →

0 · 5 marks

Discuss working of grid layout with example. [5]

Grid layout is a CSS-based two-dimensional layout system that allows developers to create complex, responsive web page layouts by dividing the page into rows and columns, forming a grid of cells where content can be placed. - A grid container is created by setting display: grid on a parent elemen...

Open this answer on its own page →

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 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:

ComponentPurpose
FrameContainer window for the form
TextFieldInput fields for user data (2 fields)
ButtonClickable buttons with captions 'OK' and 'CANCEL'
FlowLayoutArranges components in a row
ActionListenerHandles 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
Open this answer on its own page →

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]

Feature Description ---------------------- JFrame Main window container JLabel Display text labels for input fields JTextField Input fields for numbers; result field is non-editable JButton Four operation buttons ActionListener Interface to handle button click events GridLayout Arranges component...

Open this answer on its own page →

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]

Key Components: 1. Labels (4): Display field names for Principal, Time, Rate, and Interest 2. Text Boxes (3): Input fields for Principal, Time, and Rate; Interest field is read-only 3. Buttons (2): - "Simple Interest": Calculates SI using formula SI = (P × T × R) / 100 - "Reset": Clears all input...

Open this answer on its own page →

Mouse events and keyboard events

2082 · 5 marks

Write a program to illustrate the concept of Mouse Events. [5]

Event Type Method Description -------------------------------- Mouse Click mouseClicked() Triggered when mouse button is clicked Mouse Press mousePressed() Triggered when mouse button is pressed down Mouse Release mouseReleased() Triggered when mouse button is released Mouse Enter mouseEntered() ...

Open this answer on its own page →

2081 · 5 marks

Write a program to show the use of mouse event. [5]

Since reference notes are not provided, this answer follows standard web-based mouse event handling appropriate for BSc CSIT curriculum. Event Description -------------------- mouseover Triggered when mouse pointer enters element mouseout Triggered when mouse pointer leaves element click Triggere...

Open this answer on its own page →

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]

JPanel is a lightweight container component in Java Swing used in the following scenarios: 1. Organizing Components: JPanel groups related GUI components together logically. For example, grouping buttons, text fields, or labels that form a functional unit. 2. Layout Management: JPanel allows you ...

Open this answer on its own page →

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]

Key Components: 1. Window Creation: tk.Tk() creates the main application window with title and size. 2. Global Counter: clickcount variable stores the number of button clicks. 3. Click Handler Function: onbuttonclick() function: - Increments the counter by 1 each time button is clicked - Updates ...

Open this answer on its own page →

0 · 5 marks

What is action command? How it is used in java programs? Explain with example. [5]

An action command is a string that identifies or labels an action event in Java. It is associated with components like buttons, menu items, and text fields to distinguish between different user actions and determine what operation should be performed when an event occurs. Action commands are used...

Open this answer on its own page →