home
0%
Progress
CBSE Code 802 | Unit 3: Java Programming

05. GUI Development with Java Swing

JFrame, JButton, JTextField, JCheckBox, JRadioButton, ButtonGroup, Delegation Event Model.

Unit 3: Java Programming

Chapter 5: GUI Development with Java Swing

1. What is Java Swing?

Java Swing is a lightweight, platform-independent Graphical User Interface (GUI) toolkit belonging to the Java Foundation Classes (JFC). - Located in the javax.swing.* package. - Replaced the older AWT (Abstract Window Toolkit) which was heavyweight and platform-dependent.


2. Core Swing Components and Properties

                            Component
                                |
                            Container
                                |
                 +--------------+--------------+
                 |                             |
               Window                       JComponent
                 |                             |
               JFrame         +----------------+----------------+
                              |                |                |
                            JPanel          JButton          JLabel
                                            JTextField       JCheckBox
                                            JTextArea        JRadioButton

Key Swing Controls Table

Control Name Purpose Commonly Used Methods / Properties
JFrame Main top-level application window frame setTitle(), setSize(), setVisible(true)
JLabel Displays static text or icons (non-editable) setText(), getText(), setIcon()
JTextField Single-line editable text input box getText(), setText(), setEditable()
JPasswordField Single-line password box (masks input with *) getPassword()
JTextArea Multi-line text input area with scroll support append(), setRows(), setColumns()
JButton Clickable push button to trigger actions setText(), addActionListener()
JCheckBox Toggle box allowing multiple option selections isSelected(), setSelected()
JRadioButton Option button in a mutually exclusive group isSelected() (requires ButtonGroup)
ButtonGroup Logical group ensuring only 1 radio button is active add()
JComboBox Dropdown selection list addItem(), getSelectedItem(), getSelectedIndex()

3. Event Handling in Java Swing

GUIs are event-driven. When a user interacts with a control (e.g., clicking a button), an Event is generated, transmitted to an Event Listener, and handled inside an Event Handler method.

The Delegation Event Model

  1. Event Source: The GUI component generating the event (e.g., JButton).
  2. Event Object: Encapsulates information about the event (e.g., ActionEvent).
  3. Event Listener: An interface containing the callback handler method (e.g., ActionListener).
import javax.swing.*;
import java.awt.event.*;

public class SimpleCalcGUI extends JFrame implements ActionListener {
    JTextField txt1, txt2;
    JLabel lblResult;
    JButton btnAdd;

    public SimpleCalcGUI() {
        setTitle("Quick Adder");
        setSize(300, 200);
        setLayout(null);

        txt1 = new JTextField();
        txt1.setBounds(50, 20, 100, 30);
        add(txt1);

        txt2 = new JTextField();
        txt2.setBounds(50, 60, 100, 30);
        add(txt2);

        btnAdd = new JButton("Add");
        btnAdd.setBounds(50, 100, 100, 30);
        btnAdd.addActionListener(this); // Register Listener
        add(btnAdd);

        lblResult = new JLabel("Result: 0");
        lblResult.setBounds(50, 140, 150, 30);
        add(lblResult);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    // Event Handler Method
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == btnAdd) {
            int a = Integer.parseInt(txt1.getText());
            int b = Integer.parseInt(txt2.getText());
            int sum = a + b;
            lblResult.setText("Result: " + sum);
        }
    }

    public static void main(String[] args) {
        new SimpleCalcGUI();
    }
}

4. Board Exam Focus & Practical Viva Questions

  1. Why is ButtonGroup essential when using JRadioButton?
  2. Ans: Without adding radio buttons to a ButtonGroup, each radio button acts independently and the user can check multiple buttons simultaneously, violating mutual exclusivity.
  3. Which method is used to extract text entered into a JTextField?
  4. Ans: getText() which returns a String. To convert to integer, use Integer.parseInt().
  5. Differentiate between JTextField and JTextArea.
  6. Ans: JTextField allows single-line text input, whereas JTextArea allows multi-line text input.

Entity Details

Create New Item

help

Submit Technical Query

Have a question or run into an issue? Describe it below, upload an optional screenshot, and our engineering team will answer it!

image Attach image (optional)

Submit Feedback

build Free Developer Utility Free Tool
gavel

Privacy & Legal Disclaimer

1. Client-Side Browser Processing

All utility tools on DeepEngineerHub (including Image to PDF, Text Formatters, JSON Converters, and Encryptors) execute 100% locally within your client browser using WebAssembly and JavaScript. No uploaded images, text, or documents are transmitted, collected, or stored on remote servers.

2. Limitation of Liability ("As-Is" Provision)

Tools and services are provided free of charge for convenience and educational purposes "as-is" without warranties of any kind. DeepEngineerHub shall not be held liable for any data loss, formatting inconsistencies, or indirect damages resulting from tool usage.

3. Open Source & Third-Party Software

Certain utilities utilize open-source client libraries (such as jsPDF, Mermaid.js, Pyodide) licensed under MIT, Apache, or BSD open licenses. All intellectual property remains with their respective copyright holders.