Exploring Swing Controls: JFrame, JLabel, JTextField & Swing Buttons
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).
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)!
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
JFramejavax.swing.JFrame), implementing WindowConstants to define close behavior (EXIT_ON_CLOSE, DISPOSE_ON_CLOSE, HIDE_ON_CLOSE, DO_NOTHING_ON_CLOSE).JLabel and ImageIconJComponent displaying read-only text and/or an Icon (ImageIcon loaded from file/URL) aligned via SwingConstants (LEFT, RIGHT, CENTER, LEADING, TRAILING).JTextFieldJTextComponent, backed by the Document model; fires ActionEvent on Enter and CaretEvent on cursor move.ButtonGroupAbstractButton (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). FiresActionEvent; read command viaae.getActionCommand()or customize viabtn.setActionCommand(...).JToggleButton: Two-state button (pushed/released); superclass ofJCheckBoxandJRadioButton! Constructor:JToggleButton(String str). FiresItemEventhandled byItemListener.itemStateChanged(ItemEvent ie); check state withboolean isSelected().JCheckBox: Independent toggle checkbox (JCheckBox(String str),JCheckBox(String str, boolean state)). FiresItemEvent; multiple checkboxes can be selected simultaneously.JRadioButton+ButtonGroup: Mutually exclusive options (JRadioButton(String str)). Add buttons to aButtonGroup bg = new ButtonGroup(); bg.add(rb1); bg.add(rb2);so selecting one automatically deselects the others (note:ButtonGroupis a logical group, NOT a visual container—you still add eachJRadioButtonto theJFrame/JPanel!).
5. Working Principle: How ButtonGroup Enforces Mutual Exclusion
- Create
JRadioButton opt1 = new JRadioButton("CSE");andopt2 = new JRadioButton("ECE");. - Add both to
JPanel/JFramefor display AND add both toButtonGroup bgfor logic. - When user clicks
opt2,ButtonGroupunselectsopt1'sButtonModelautomatically before selectingopt2.
6. Examination-Ready Diagrams
AWT and Swing Component Hierarchy
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).
- Object -> Component -> Container: Core AWT foundation classes (
java.awt). - Top-Level Heavyweight Containers:
Window->Frame->JFrameandDialog->JDialog(do NOT extendJComponent). - JComponent (Lightweight): Root of Swing controls (
JLabel,JPanel,JTextComponent -> JTextField,AbstractButton -> JButton, JToggleButton -> JCheckBox, JRadioButton).
java.lang.Object->java.awt.Component->java.awt.Container.- From
Container, top-level containers branch viaWindow/Frame/Dialog->JFrame/JDialog. - From
Container,javax.swing.JComponentbranches into all lightweight Swing widgets andJPanel.
- Draw
Object->Component->Containerat 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
ButtonGroup mutual exclusion, and ActionListener/ItemListener feedback.| 1 | import javax.swing.*; |
| 2 | import java.awt.*; |
| 3 | import java.awt.event.*; |
| 4 | |
| 5 | public 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 | } |
SwingControlsDemo compiled & verified cleanly (headless mode).
JFrameJLabelJTextFieldJButtonJCheckBoxJRadioButtonButtonGroup- Forgetting to add
JRadioButtons to aButtonGroup(allowing multiple radio buttons to stay selected at once). - Adding the
ButtonGroupitself toJFrame(add(branchGroup)-> COMPILE ERROR;ButtonGroupis not aComponent!). - Forgetting
setVisible(true)orsetSize(...)onJFrame.
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, andJFrame.EXIT_ON_CLOSE. - Highlight
JToggleButtonas the superclass of BOTHJCheckBoxandJRadioButton, andAbstractButtonas parent of all four!
Memory Techniques & Revision
- Button Family Tree:
AbstractButton -> { JButton, JToggleButton -> { JCheckBox, JRadioButton } }.
Common Pitfalls to Avoid
- Calling
frame.add(buttonGroup)—ButtonGrouponly manages selection logic; eachJRadioButtonmust 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 byDocument; firesActionEvent(Enter) andCaretEvent. Method:getText(). - JButton: Push button extending
AbstractButton(JButton(String),JButton(String, Icon)). FiresActionEvent;setActionCommand(),getActionCommand(). - JCheckBox & JRadioButton: Extend
JToggleButton; fireItemEvent(ItemListener).JCheckBoxsupports multi-select;JRadioButtonusesButtonGroupfor mutual exclusion. State checked viaisSelected().
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?