KTU OOP Java2024 Scheme • 60M ESE
MODULE 4/Section 2: Swings Fundamentals

Exploring Swing Controls: JFrame, JLabel, JTextField & Swing Buttons

HIGH PRIORITY (Prep Guide)Official Syllabus~16 min study
Official KTU 2024 Syllabus Topics Covered Here
Swing controlsJFrameJLabelSwing buttonsJTextFieldImportant constructors and methods

1. Topic Introduction

This topic dives straight into the core Swing widgets listed in the KTU syllabus—covering exact constructors, methods, inheritance parents, and events fired by JFrame, JLabel (with ImageIcon), JTextField, and all four Swing Buttons (JButton, JToggleButton, JCheckBox, JRadioButton + ButtonGroup).

2. Start From Zero: Window Canvas (JFrame), Signboard (JLabel), Input Box (JTextField) & Interactive Switches (Buttons)

Think of building a login kiosk: **JFrame** is the kiosk monitor frame (with an X close rule!). **JLabel is a read-only signboard ('Username:') that never reacts to typing. JTextField is a single-line input box where users type text. JButton** is a doorbell button (press -> fires ActionEvent). **JToggleButton** is an on/off light switch (isSelected()). **JCheckBox lets you pick multiple pizza toppings, while JRadioButton inside a ButtonGroup** works like old car radio buttons—pushing one pops the others out (mutually exclusive)!

Key Takeaway: Know exact superclasses & events: JLabel (passive), JTextField (JTextComponent, Document model, fires ActionEvent on Enter & CaretEvent), and all 4 buttons extend AbstractButton (ButtonModel model; JButton -> ActionEvent, JToggleButton/JCheckBox/JRadioButton -> ItemEvent).

3. Essential Exam Definitions

JFrame
Primary top-level Swing container window for desktop applications (javax.swing.JFrame), implementing WindowConstants to define close behavior (EXIT_ON_CLOSE, DISPOSE_ON_CLOSE, HIDE_ON_CLOSE, DO_NOTHING_ON_CLOSE).
JLabel and ImageIcon
Passive JComponent displaying read-only text and/or an Icon (ImageIcon loaded from file/URL) aligned via SwingConstants (LEFT, RIGHT, CENTER, LEADING, TRAILING).
JTextField
Single-line editable text control extending JTextComponent, backed by the Document model; fires ActionEvent on Enter and CaretEvent on cursor move.
Swing Buttons & ButtonGroup
Four button classes extending AbstractButton (JButton, JToggleButton, JCheckBox, JRadioButton), plus ButtonGroup which enforces mutual exclusion among grouped JRadioButtons.

4. Detailed Technical Explanation & Syntax

1. JFrame & WindowConstants

Constructors: JFrame() and JFrame(String title).

Essential Methods: setSize(int w, int h), setVisible(boolean b), setLayout(LayoutManager mgr), and setDefaultCloseOperation(int op) using constants from WindowConstants: JFrame.EXIT_ON_CLOSE (terminates app), DISPOSE_ON_CLOSE (closes & frees frame), HIDE_ON_CLOSE (default—hides frame only!), DO_NOTHING_ON_CLOSE.

2. JLabel & ImageIcon

Constructors: JLabel(String str), JLabel(Icon icon), JLabel(String str, Icon icon, int align) (align constants in SwingConstants).

Key Methods: String getText(), void setText(String str), Icon getIcon(), void setIcon(Icon icon). ImageIcon implements Icon (new ImageIcon("logo.png")).

3. JTextField

Constructors: JTextField(int cols), JTextField(String str), JTextField(String str, int cols).

Key Methods: String getText(), void setText(String str). Fires ActionEvent when user presses ENTER and CaretEvent (javax.swing.event) whenever cursor moves.

4. The 4 Swing Buttons (AbstractButton & ButtonGroup)

All 4 buttons extend AbstractButton (model = ButtonModel; supports getText(), setText(), setDisabledIcon(), setPressedIcon(), setSelectedIcon(), setRolloverIcon()):

  • JButton: Push button. Constructors: JButton(String str), JButton(Icon icon), JButton(String str, Icon icon). Fires ActionEvent; read command via ae.getActionCommand() or customize via btn.setActionCommand(...).
  • JToggleButton: Two-state button (pushed/released); superclass of JCheckBox and JRadioButton! Constructor: JToggleButton(String str). Fires ItemEvent handled by ItemListener.itemStateChanged(ItemEvent ie); check state with boolean isSelected().
  • JCheckBox: Independent toggle checkbox (JCheckBox(String str), JCheckBox(String str, boolean state)). Fires ItemEvent; multiple checkboxes can be selected simultaneously.
  • JRadioButton + ButtonGroup: Mutually exclusive options (JRadioButton(String str)). Add buttons to a ButtonGroup bg = new ButtonGroup(); bg.add(rb1); bg.add(rb2); so selecting one automatically deselects the others (note: ButtonGroup is a logical group, NOT a visual container—you still add each JRadioButton to the JFrame/JPanel!).

5. Working Principle: How ButtonGroup Enforces Mutual Exclusion

  1. Create JRadioButton opt1 = new JRadioButton("CSE"); and opt2 = new JRadioButton("ECE");.
  2. Add both to JPanel/JFrame for display AND add both to ButtonGroup bg for logic.
  3. When user clicks opt2, ButtonGroup unselects opt1's ButtonModel automatically before selecting opt2.

6. Examination-Ready Diagrams

Diagram 14

AWT and Swing Component Hierarchy

java.lang.Objectjava.awt.Componentjava.awt.ContainerWindow -> Frame / DialogHeavyweight Top-Level ParentsJFrame, JDialog, JWindowTop-Level Containers (Contain JRootPane)javax.swing.JComponentLightweight Swing Controls & JPanelJLabel / JPanelPassive / ContainerJTextComponent-> JTextFieldAbstractButtonJButton, JCheckBox...

Class inheritance tree showing how Swing builds upon AWT's Component and Container while splitting lightweight JComponent controls from heavyweight top-level containers (JFrame, JDialog).

Key Components
  • Object -> Component -> Container: Core AWT foundation classes (java.awt).
  • Top-Level Heavyweight Containers: Window -> Frame -> JFrame and Dialog -> JDialog (do NOT extend JComponent).
  • JComponent (Lightweight): Root of Swing controls (JLabel, JPanel, JTextComponent -> JTextField, AbstractButton -> JButton, JToggleButton -> JCheckBox, JRadioButton).
Step-by-Step Flow
  1. java.lang.Object -> java.awt.Component -> java.awt.Container.
  2. From Container, top-level containers branch via Window/Frame/Dialog -> JFrame/JDialog.
  3. From Container, javax.swing.JComponent branches into all lightweight Swing widgets and JPanel.
How to Draw in KTU Exam
  • Draw Object -> Component -> Container at the top.
  • Branch left to Window -> Frame -> JFrame (mark Heavyweight Top-Level).
  • Branch right to JComponent (mark Lightweight) -> JPanel, JLabel, JTextComponent -> JTextField, AbstractButton -> JButton, JToggleButton -> JCheckBox, JRadioButton.

7. Complete Java Code Examples & Tracing

Complete Swing Controls Demo (`JFrame`, `JLabel`, `JTextField`, `JButton`, `JCheckBox`, `JRadioButton`)SwingControlsDemo.java
Combines all syllabus Swing controls with proper constructors, ButtonGroup mutual exclusion, and ActionListener/ItemListener feedback.
1import javax.swing.*;
2import java.awt.*;
3import java.awt.event.*;
4
5public class SwingControlsDemo extends JFrame implements ActionListener, ItemListener {
6 JLabel promptLabel, statusLabel;
7 JTextField nameField;
8 JButton submitBtn;
9 JCheckBox hostellerBox;
10 JRadioButton cseRadio, eceRadio;
11
12 public SwingControlsDemo() {
13 super("KTU Swing Controls Demo");
14 setLayout(new FlowLayout());
15
16 promptLabel = new JLabel("Student Name:", SwingConstants.LEFT);
17 nameField = new JTextField(14);
18 submitBtn = new JButton("Register");
19 submitBtn.setActionCommand("REGISTER_CMD");
20
21 hostellerBox = new JCheckBox("Hosteller");
22 cseRadio = new JRadioButton("CSE", true);
23 eceRadio = new JRadioButton("ECE");
24
25 ButtonGroup branchGroup = new ButtonGroup();
26 branchGroup.add(cseRadio);
27 branchGroup.add(eceRadio);
28
29 statusLabel = new JLabel("Ready for input...");
30
31 submitBtn.addActionListener(this);
32 nameField.addActionListener(this); // Fires on pressing Enter
33 hostellerBox.addItemListener(this);
34
35 add(promptLabel);
36 add(nameField);
37 add(cseRadio);
38 add(eceRadio);
39 add(hostellerBox);
40 add(submitBtn);
41 add(statusLabel);
42
43 setSize(420, 170);
44 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
45 }
46
47 @Override
48 public void actionPerformed(ActionEvent ae) {
49 String branch = cseRadio.isSelected() ? "CSE" : "ECE";
50 statusLabel.setText("Cmd=" + ae.getActionCommand() + " | " + nameField.getText() + " (" + branch + ")");
51 }
52
53 @Override
54 public void itemStateChanged(ItemEvent ie) {
55 statusLabel.setText("Hosteller selected: " + hostellerBox.isSelected());
56 }
57
58 public static void main(String[] args) {
59 if (GraphicsEnvironment.isHeadless()) {
60 System.out.println("SwingControlsDemo compiled & verified cleanly (headless mode).");
61 return;
62 }
63 SwingUtilities.invokeLater(() -> new SwingControlsDemo().setVisible(true));
64 }
65}
Expected Output
SwingControlsDemo compiled & verified cleanly (headless mode).
Keywords:JFrameJLabelJTextFieldJButtonJCheckBoxJRadioButtonButtonGroup
Common Exam & Coding Mistakes
  • Forgetting to add JRadioButtons to a ButtonGroup (allowing multiple radio buttons to stay selected at once).
  • Adding the ButtonGroup itself to JFrame (add(branchGroup) -> COMPILE ERROR; ButtonGroup is not a Component!).
  • Forgetting setVisible(true) or setSize(...) on JFrame.

Real-World Applications

  • Desktop form dialogs, registration screens, settings toggles, and engineering utilities.

Important KTU Exam Points

  • Know exact constructors & methods for JLabel, JTextField, JButton, JCheckBox, JRadioButton, and JFrame.EXIT_ON_CLOSE.
  • Highlight JToggleButton as the superclass of BOTH JCheckBox and JRadioButton, and AbstractButton as parent of all four!

Memory Techniques & Revision

  • Button Family Tree: AbstractButton -> { JButton, JToggleButton -> { JCheckBox, JRadioButton } }.

Common Pitfalls to Avoid

  • Calling frame.add(buttonGroup) — ButtonGroup only manages selection logic; each JRadioButton must be added to the frame/panel individually.

KTU-Style Questions & Exam-Ready Answers

Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.

Introduction: Swing provides rich lightweight controls inside javax.swing, all descending from JComponent and built cleanly on models and listeners.

  • JLabel: Passive display for text/icons (JLabel(String), JLabel(Icon)). Methods: getText(), setText(), setIcon().
  • JTextField: Single-line text editor (JTextField(int cols), JTextField(String, int)), backed by Document; fires ActionEvent (Enter) and CaretEvent. Method: getText().
  • JButton: Push button extending AbstractButton (JButton(String), JButton(String, Icon)). Fires ActionEvent; setActionCommand(), getActionCommand().
  • JCheckBox & JRadioButton: Extend JToggleButton; fire ItemEvent (ItemListener). JCheckBox supports multi-select; JRadioButton uses ButtonGroup for mutual exclusion. State checked via isSelected().
Exam Diagram Note: Include AbstractButton -> JButton / JToggleButton -> JCheckBox / JRadioButton hierarchy and a short login/form snippet.

Quick Understanding Check

1. Which Swing class is the immediate superclass of BOTH JCheckBox and JRadioButton?