A class implements MouseListener, MouseMotionListener and KeyListener directly. How many methods must it define? How many if WindowListener is added? How do adapters change the answer?
Java GUIs are built from components placed in containers, arranged by layout managers and brought to life by events. Covers the AWT hierarchy and components, the layout managers, the event delegation model with its listeners and adapters, Swing's lightweight J-components, and AWT vs Swing.
Java has had three GUI toolkits. The Abstract Window Toolkit (AWT), in java.awt since JDK 1.0, wraps the operating system's own widgets. Swing, released in 1997 as part of the Java Foundation Classes (JFC) and bundled from Java 1.2, lives in javax.swing and draws its components itself, in Java. JavaFX (2008; bundled with Java 8, a separate OpenJFX download since Java 11) is the modern scene-graph toolkit. Exam questions focus on AWT and Swing.
Every Java GUI has the same four ingredients: components (buttons, labels, text fields), containers that hold components (frames, panels), layout managers that position the components inside a container, and events with listeners that respond to the user.
| Class | What it is | Key methods |
|---|---|---|
| Component | Abstract root of every visual element | setSize, setLocation, setBounds, setVisible, setBackground, setForeground, setFont, paint, repaint, addXxxListener |
| Container | A component that holds other components | add, remove, setLayout, getComponents, validate |
| Panel | The simplest container, used to group components inside others | Default FlowLayout |
| Window | A top-level window with no title bar or border | pack, setVisible, dispose; default BorderLayout |
| Frame | A top-level window with title bar, border and optional menu bar | setTitle, setMenuBar, setResizable |
| Dialog | A pop-up window owned by a Frame; can be modal | setModal; FileDialog chooses files |
import java.awt.*;
import java.awt.event.*;
public class HelloFrame extends Frame {
HelloFrame() {
super("KSHB Allotment"); // title bar text
setLayout(new FlowLayout()); // replace the default BorderLayout
add(new Label("Applicant name:"));
add(new TextField(20)); // 20 columns wide
add(new Button("Submit"));
setSize(400, 120);
addWindowListener(new WindowAdapter() { // without this the close box does nothing
public void windowClosing(WindowEvent e) { dispose(); }
});
setVisible(true); // frames start out invisible
}
public static void main(String[] args) { new HelloFrame(); }
}| Component | Purpose | Creating one | Event it generates |
|---|---|---|---|
| Label | Read-only text | new Label("Name", Label.RIGHT) | — |
| Button | A push button | new Button("OK") | ActionEvent |
| TextField | One line of editable text | new TextField(20) | ActionEvent (Enter key), TextEvent |
| TextArea | Several lines of text | new TextArea(5, 30) | TextEvent |
| Checkbox | An on/off box | new Checkbox("Married") | ItemEvent |
| Checkbox + CheckboxGroup | Radio buttons: only one of the group can be on | new Checkbox("Male", group, true) | ItemEvent |
| Choice | A drop-down list showing one item | choice.add("Kochi") | ItemEvent |
| List | A scrolling list, single or multiple selection | new List(4, true) | ItemEvent; ActionEvent on double-click |
| Scrollbar | Pick a value from a range | new Scrollbar(Scrollbar.HORIZONTAL, 0, 10, 0, 100) | AdjustmentEvent |
| Canvas | A blank area for custom drawing | a subclass overriding paint(Graphics g) | Mouse and key events |
| MenuBar, Menu, MenuItem | Menus attached to a Frame | frame.setMenuBar(bar) | ActionEvent (MenuItem) |
setLayout(new FlowLayout()); // a Frame defaults to BorderLayout
CheckboxGroup gender = new CheckboxGroup(); // makes the boxes mutually exclusive
Checkbox male = new Checkbox("Male", gender, true); // initially selected
Checkbox female = new Checkbox("Female", gender, false);
add(male);
add(female);
MenuBar bar = new MenuBar();
Menu file = new Menu("File");
MenuItem save = new MenuItem("Save");
file.add(save);
file.addSeparator();
file.add(new MenuItem("Exit"));
bar.add(file);
setMenuBar(bar); // AWT menus belong to a FramegetSelectedCheckbox() tells which is on). In Swing they are JRadioButtons added to a ButtonGroup.A layout manager decides the size and position of every component in a container and recomputes them whenever the container is resized, so the same program looks right on any screen and with any font. Set it with container.setLayout(manager); every container has a default.
| Layout manager | How it arranges components | Default for |
|---|---|---|
| FlowLayout | Left to right in rows, wrapping like words in a paragraph; centred by default with 5-pixel gaps | Panel, Applet, JPanel |
| BorderLayout | Five regions — NORTH, SOUTH, EAST, WEST, CENTER; CENTER takes all the leftover space | Window, Frame, Dialog, JFrame's content pane |
| GridLayout(rows, cols) | A grid of equal-sized cells filled row by row | — |
| CardLayout | A stack of 'cards', one visible at a time: next(), previous(), first(), last(), show(parent, name) | — |
| GridBagLayout | A flexible grid: components may span cells and stretch, controlled by GridBagConstraints (gridx, gridy, gridwidth, weightx, fill, anchor, insets) | — |
| null (no layout manager) | Absolute positions via setBounds(x, y, w, h); ignores resizing and font changes | — |
| BoxLayout, GroupLayout, SpringLayout (Swing) | A single row or column; layouts used by GUI builders | — |
Frame f = new Frame("Calculator"); // BorderLayout by default
TextField display = new TextField();
f.add(display, BorderLayout.NORTH); // a strip across the top
Panel keys = new Panel(new GridLayout(4, 4, 2, 2)); // 4 x 4 equal keys, 2-pixel gaps
String labels = "789/456*123-0.=+";
for (char c : labels.toCharArray())
keys.add(new Button(String.valueOf(c)));
f.add(keys, BorderLayout.CENTER); // the keys take the remaining space
f.add(new Label("KSHB calc"), BorderLayout.SOUTH);
f.setSize(240, 280);
f.setVisible(true);add(comp) with no constraint means CENTER, and each region holds only one component — a later add to the same region replaces the earlier one.GridLayout(2, 3) with 7 components becomes 2 rows × 4 columns.JDK 1.0 used an inheritance-based model: every event travelled up the containment hierarchy to handleEvent() / action() methods until some component dealt with it — wasteful, because every event went everywhere, and messy, because UI and logic were mixed. JDK 1.1 replaced it with the delegation event model, in which a component delegates the handling of its events to separate listener objects.
source.addActionListener(listener) registers it (removeActionListener unregisters). When the event occurs, the source calls the method of every registered listener, passing the event object — on the AWT event-dispatch thread.| Event class | Generated by | Listener interface | Methods (count) |
|---|---|---|---|
| ActionEvent | Button click, Enter in a TextField, MenuItem, double-click in a List | ActionListener | actionPerformed (1) |
| ItemEvent | Checkbox, Choice, List selection, CheckboxMenuItem | ItemListener | itemStateChanged (1) |
| TextEvent | Text changed in a TextField or TextArea | TextListener | textValueChanged (1) |
| AdjustmentEvent | Scrollbar moved | AdjustmentListener | adjustmentValueChanged (1) |
| KeyEvent | Keyboard | KeyListener | keyPressed, keyReleased, keyTyped (3) |
| MouseEvent | Mouse buttons, entering and leaving | MouseListener | mouseClicked, mousePressed, mouseReleased, mouseEntered, mouseExited (5) |
| MouseEvent | Mouse movement | MouseMotionListener | mouseDragged, mouseMoved (2) |
| MouseWheelEvent | Wheel rotation | MouseWheelListener | mouseWheelMoved (1) |
| FocusEvent | Focus gained or lost | FocusListener | focusGained, focusLost (2) |
| WindowEvent | Window opened, closing, minimised … | WindowListener | windowOpened, windowClosing, windowClosed, windowIconified, windowDeiconified, windowActivated, windowDeactivated (7) |
| ComponentEvent | Component moved, resized, shown or hidden | ComponentListener | componentMoved, componentResized, componentShown, componentHidden (4) |
| ContainerEvent | Component added to or removed from a container | ContainerListener | componentAdded, componentRemoved (2) |
InputEvent is the abstract parent of KeyEvent and MouseEvent (isShiftDown(), getWhen()). MouseEvent offers getX(), getY() and getClickCount(); KeyEvent offers getKeyChar() and getKeyCode() (compare with constants such as KeyEvent.VK_ENTER); ActionEvent offers getActionCommand(), normally the button's label. The step-through sequence on this page follows one button click from start to finish.
implements ActionListener, then button.addActionListener(this).import java.awt.*;
import java.awt.event.*;
public class ClickCounter extends Frame implements ActionListener {
private int count = 0;
private final Label shown = new Label("Clicks: 0 ");
private final Button plus = new Button("+1");
private final Button reset = new Button("Reset");
ClickCounter() {
super("Counter");
setLayout(new FlowLayout());
add(shown); add(plus); add(reset);
plus.addActionListener(this); // style 1: this class listens
reset.addActionListener(e -> { // style 4: a lambda
count = 0;
shown.setText("Clicks: 0");
});
addWindowListener(new WindowAdapter() { // style 3: anonymous adapter subclass
@Override public void windowClosing(WindowEvent e) { System.exit(0); }
});
setSize(300, 100);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) { // runs on the event dispatch thread
count++;
shown.setText("Clicks: " + count);
}
public static void main(String[] args) { new ClickCounter(); }
}Implementing WindowListener directly would force you to write all seven methods even if you care only about windowClosing. An adapter class is an abstract class that implements a listener interface with empty method bodies, so you subclass it and override just what you need.
| Adapter class | Implements | Typical override |
|---|---|---|
| WindowAdapter | WindowListener (plus WindowStateListener and WindowFocusListener) | windowClosing |
| MouseAdapter | MouseListener, MouseMotionListener, MouseWheelListener | mouseClicked, mousePressed |
| MouseMotionAdapter | MouseMotionListener | mouseDragged |
| KeyAdapter | KeyListener | keyPressed |
| FocusAdapter | FocusListener | focusLost |
| ComponentAdapter, ContainerAdapter | ComponentListener, ContainerListener | componentResized |
windowclosing) compiles as a brand-new method that is never called; @Override turns that mistake into a compile error.Swing components are lightweight: instead of asking the operating system for a native widget (a peer) for every button, Swing paints each component itself, in Java, onto its top-level window. They therefore look and behave the same on every platform, can be transparent or non-rectangular, and can show icons and HTML text. Only the top-level containers — JFrame, JDialog, JWindow (and the removed JApplet) — are heavyweight. Every Swing component extends JComponent, itself a subclass of AWT's Container.
| Swing class | AWT counterpart / purpose |
|---|---|
| JFrame, JDialog | Frame, Dialog — components go into the content pane |
| JPanel | Panel (default FlowLayout) |
| JButton, JLabel | Button, Label — and they can display icons |
| JTextField, JPasswordField, JTextArea | TextField, TextArea; JPasswordField masks what is typed |
| JCheckBox; JRadioButton + ButtonGroup | Checkbox; Checkbox + CheckboxGroup |
| JComboBox, JList | Choice, List |
| JTable, JTree, JTabbedPane, JSplitPane | No AWT equivalent: tables, trees, tabs, split views |
| JScrollPane | ScrollPane — scrolls any component |
| JMenuBar, JMenu, JMenuItem | MenuBar, Menu, MenuItem |
| JOptionPane, JFileChooser, JProgressBar, JSlider | Ready-made dialogs and controls |
import javax.swing.*;
import java.awt.BorderLayout;
public class SwingHello {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> { // build the GUI on the EDT
JFrame f = new JFrame("KSHB Enquiry");
JLabel status = new JLabel("Ready");
JTextField name = new JTextField(15);
JButton greet = new JButton("Greet");
greet.addActionListener(e -> status.setText("Hello, " + name.getText()));
JPanel top = new JPanel(); // FlowLayout by default
top.add(new JLabel("Name:"));
top.add(name);
top.add(greet);
f.add(top, BorderLayout.NORTH); // goes into the content pane
f.add(status, BorderLayout.SOUTH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // the default is HIDE_ON_CLOSE
f.setSize(380, 120);
f.setVisible(true);
});
}
}Pluggable look-and-feel: UIManager.setLookAndFeel(…) switches every component between Metal (the cross-platform default), Nimbus or the host system's look. MVC: each Swing component keeps its data in a separate model — ButtonModel, Document for text, TableModel for JTable — while the view and controller are combined into a UI delegate (Swing's 'separable model architecture'). Swing is not thread-safe: create and change components only on the Event Dispatch Thread (SwingUtilities.invokeLater) and run long jobs in the background (SwingWorker) so the window never freezes.
| Point | AWT | Swing |
|---|---|---|
| Package | java.awt | javax.swing (built on top of java.awt) |
| Component weight | Heavyweight — each component has a native peer | Lightweight — painted by Java (except the top-level containers) |
| Look and feel | That of the host operating system | Pluggable; identical on every OS by default |
| Component set | Basic | Rich: tables, trees, tabs, sliders, progress bars, icons |
| Architecture | No model–view separation | Model–view (separable model) design |
| Resources | Lighter but limited | Heavier, far more capable |
| Class names | Button, Frame, TextField | JButton, JFrame, JTextField |
| Threading rule | Events arrive on the AWT event thread | All GUI work on the Event Dispatch Thread |
Try the problem first, then reveal the working one step at a time.
A class implements MouseListener, MouseMotionListener and KeyListener directly. How many methods must it define? How many if WindowListener is added? How do adapters change the answer?
Five Buttons, labelled 1 to 5, are added to a Frame with plain add(b) calls, and the frame is shown. What appears? What changes if they are added to a Panel first, or to the frame with BorderLayout constraints?
Design an AWT login window with labels and fields for user name and password plus Login and Cancel buttons. Choose the layout, the components and the listeners.
How are 7 components arranged by GridLayout(2, 3)? By GridLayout(0, 3)? By GridLayout(3, 0) with 8 components?
Give the default layout manager of: Frame, Panel, Applet, Dialog, Window, JPanel, and a JFrame's content pane.
Name the listener interface and the method that handle: (a) pressing Enter in a TextField; (b) ticking a Checkbox; (c) clicking a window's close box; (d) dragging the mouse; (e) typing a character; (f) moving a Scrollbar.
Why is there no ActionAdapter class? Write a window-closing handler for an AWT Frame f using an adapter.
Write AWT code (inside a Frame constructor) for three radio buttons — Kochi, Thrissur, Kozhikode — with Kochi selected, and print the chosen district whenever the selection changes.
A Swing program's JFrame disappears when its close box is clicked, but the program keeps running in the background. Explain and fix. Why should the frame be built inside SwingUtilities.invokeLater?
10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.