Unit 2: GUI and Event Handling
I. Orientation
Java Swing is a GUI toolkit introduced with the Java Foundation Classes in Java 1.2 (1998). It provides platform-independent windows, controls, layout systems, drawing facilities, and an event-driven programming model in which user actions determine program flow.
- Core principle: A Swing program creates a hierarchy of components, displays them inside top-level containers, and responds to events through registered listeners.
- Main packages:
javax.swing: Swing components such asJFrame,JPanel, andJButton.java.awt: layouts, colors, fonts, graphics, and basic event infrastructure.java.awt.event: event classes, listener interfaces, and adapter classes.
- Lightweight components: Most Swing controls are drawn by Java rather than by native operating-system peers.
- Event-driven execution: The program normally waits for events such as button clicks, mouse movement, or key presses.
- Event Dispatch Thread (EDT): Swing component creation and modification should occur on the EDT, commonly through
SwingUtilities.invokeLater. - Component hierarchy: Controls are placed in containers, while layout managers determine their sizes and positions.
II. Swing Foundations — Windows, Containers, and Controls
A. Introduction to Swing
Swing is Java’s platform-independent library for building desktop graphical user interfaces.
- Pluggable look and feel: Swing can change component appearance without changing application logic; examples include system and cross-platform look-and-feel implementations.
- Rich component set: It supplies buttons, labels, lists, tables, trees, menus, dialogs, and text controls.
- Naming convention: Swing component names usually begin with
J, as inJLabel,JButton, andJTable. - MVC influence: Many Swing components separate their data model from visual presentation; for example,
JListuses aListModel. - Threading rule: GUI startup should be scheduled safely:
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Application");
frame.setVisible(true);
});B. JFrame and JPanel
JFrame represents a top-level window, whereas JPanel is a lightweight container used to organize components or perform custom drawing.
-
JFrame:- Purpose: Provides a title bar, border, content area, and window controls.
- Configuration: Common methods include
setSize,setTitle,setLocationRelativeTo, andsetDefaultCloseOperation. - Closing behavior:
JFrame.EXIT_ON_CLOSEterminates the application when the frame closes.
-
JPanel:- Purpose: Groups related controls inside a frame and supports nested layouts.
- Default layout: A new
JPanelnormally usesFlowLayout. - Custom painting: Drawing is performed by overriding
paintComponent(Graphics g).
JFrame frame = new JFrame("Demo");
JPanel panel = new JPanel();
panel.add(new JButton("Save"));
frame.add(panel);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);C. Swing components
Swing components are reusable GUI objects that display information, receive input, or organize other components.
- Display controls:
JLabelshows text or icons;JProgressBarvisually represents progress. - Command controls:
JButtoninitiates an action, whileJMenuItemrepresents a menu command. - Text controls:
JTextFieldaccepts one line,JTextAreaaccepts multiple lines, andJPasswordFieldmasks input. - Selection controls:
JCheckBoxpermits independent choices;JRadioButtonsupports exclusive choices when placed in aButtonGroup. - Data controls:
JList,JTable, andJTreepresent collections or structured information. - Scrolling: Large components such as
JTextAreaare commonly placed inJScrollPane.
III. Interface Arrangement and Rendering
A. Layout managers
Layout managers automatically calculate component position and size, making interfaces more portable than fixed coordinates.
FlowLayout: Arranges components left to right and moves them to a new row when space is insufficient.BorderLayout: Divides a container intoNORTH,SOUTH,EAST,WEST, andCENTER; a frame’s content pane uses it by default.GridLayout: Places components in equal-sized cells arranged as rows and columns.BoxLayout: Arranges components along either the horizontalX_AXISor verticalY_AXIS.GridBagLayout: UsesGridBagConstraintsfor flexible grids with components of different sizes.- Manual positioning: A
nulllayout requiressetBounds(x, y, width, height)and is generally avoided because it adapts poorly to fonts and screen sizes.
panel.setLayout(new GridLayout(2, 2, 5, 5));
// 2 rows, 2 columns, 5-pixel horizontal and vertical gapsB. Color class
The java.awt.Color class represents colors used for component backgrounds, foregrounds, borders, and custom graphics.
- RGB model:
new Color(r, g, b)accepts red, green, and blue values from0to255. - Alpha channel:
new Color(r, g, b, a)adds transparency, where0is transparent and255is opaque. - Constants: Named values include
Color.RED,Color.BLUE,Color.WHITE, andColor.BLACK. - Component use:
setBackground(Color.YELLOW)changes a background, whilesetForeground(Color.BLUE)changes text or foreground drawing. - Concrete example:
new Color(255, 128, 0)produces orange because red is maximum, green is half intensity, and blue is absent.
C. Font class
The java.awt.Font class describes the family, style, and point size used to render text.
- Construction: The form is
new Font(name, style, size).name: Font family such as"Serif"or"Monospaced".style:Font.PLAIN,Font.BOLD,Font.ITALIC, or a combined style.size: Text size measured in points.
- Application: Components accept fonts through
setFont. - Combined style: Bitwise OR combines constants, as in
Font.BOLD | Font.ITALIC. - Example:
Font heading = new Font("SansSerif", Font.BOLD, 20);
label.setFont(heading);D. Graphics class
The abstract java.awt.Graphics class provides methods for drawing text, lines, shapes, and images on components.
- Coordinate system: The origin
(0, 0)is the component’s upper-left corner;xincreases rightward andydownward. - Drawing methods: Common operations include
drawLine,drawRect,fillRect,drawOval,fillOval, anddrawString. - Painting method: Custom Swing drawing belongs in
paintComponent, not in arbitrary application code. - Superclass call:
super.paintComponent(g)clears the previous display and paints the panel correctly. - Graphics state:
setColorandsetFontaffect subsequent drawing operations.
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillOval(20, 20, 80, 80);
g.drawString("Circle", 35, 120);
}IV. GUI Construction
A. Programs to create Graphical User Interface
A Swing GUI program normally creates a frame, selects a layout, adds components, registers listeners, and finally displays the frame.
- Construction sequence:
- Create components such as
JLabel,JTextField, andJButton. - Add them to a panel or frame under a layout manager.
- attach listeners to interactive components.
- Call
pack()orsetSize, thensetVisible(true).
- Create components such as
pack()method: Sizes the window according to the preferred sizes of its contained components.- Example program:
import javax.swing.*;
public class GreetingGUI {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame("Greeting");
JTextField name = new JTextField(12);
JButton button = new JButton("Greet");
JLabel result = new JLabel(" ");
JPanel p = new JPanel();
p.add(name);
p.add(button);
p.add(result);
button.addActionListener(e ->
result.setText("Hello, " + name.getText()));
f.add(p);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}V. Java Event Architecture
A. Event delegation model
The event delegation model separates event generation from event processing by delegating each event to registered listener objects.
- Three participants:
- Source: The component that generates the event, such as a
JButton. - Event object: An object containing event details, such as
ActionEvent. - Listener: An object whose callback method processes the event.
- Source: The component that generates the event, such as a
- Advantage: A source need not contain the response logic; different listeners can handle different actions.
- Dispatch process: User action → source creates event object → registered callback executes on the EDT.
B. Event and event source
An event represents a change in component state, while an event source is the object on which that change occurs.
- Event hierarchy: GUI event classes ultimately derive from
java.util.EventObject; many AWT events extendAWTEvent. - Examples: Clicking a button produces
ActionEvent, pressing a key producesKeyEvent, and moving a mouse producesMouseEvent. - Source retrieval:
event.getSource()returns the originating object. - Event information: A
MouseEventsupplies coordinates throughgetX()andgetY(), while aKeyEventsupplies a key code throughgetKeyCode().
C. Event listener interfaces
Listener interfaces declare callback methods that Java invokes when corresponding events occur.
ActionListener: DeclaresactionPerformed(ActionEvent e)for buttons, menu items, and text-field actions.MouseListener: Declares methods includingmouseClicked,mousePressed, andmouseReleased.MouseMotionListener: HandlesmouseMovedandmouseDragged.KeyListener: DeclareskeyPressed,keyReleased, andkeyTyped.WindowListener: Responds to window opening, closing, activation, and related state changes.
D. Registration and handling events
Registration connects a source to a listener so that the listener receives matching events.
- Registration methods: Sources provide methods such as
addActionListener,addMouseListener, andaddKeyListener. - Handling method: The listener implements the callback required by its interface.
- Removal: Methods such as
removeActionListenerdetach listeners when they are no longer required. - Example:
button.addActionListener(e -> label.setText("Button clicked"));- Threading consequence: Lengthy work inside a callback freezes repainting and input; background work should use mechanisms such as
SwingWorker.
VI. User-Input Events
A. Mouse events
Mouse events report clicking, pressing, releasing, entering, exiting, moving, and dragging within a component.
- Event interfaces:
MouseListenerhandles button and boundary events;MouseMotionListenerhandles movement and dragging. - Event data:
getX()andgetY()return component-relative coordinates;getButton()identifies the pressed button. - Click count:
getClickCount()distinguishes single and multiple clicks. - Registration:
panel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println(e.getX() + ", " + e.getY());
}
});B. Key events
Key events describe keyboard activity received by the component that currently owns keyboard focus.
- Event types:
keyPressedreports physical key depression,keyReleasedreports release, andkeyTypedreports a Unicode character. - Key information:
getKeyCode()identifies keys such asKeyEvent.VK_ENTER;getKeyChar()returns the typed character. - Focus requirement: A component generally must be focusable and own focus before its
KeyListenerreceives events. - Swing alternative: Key bindings using
InputMapandActionMapare often preferable because they manage focus conditions more reliably.
VII. Listener Implementation Techniques
A. Anonymous class listeners
An anonymous class creates and registers a one-use listener without defining a separately named class.
- Purpose: Keeps short event-handling code close to the component registration statement.
- Syntax: The interface or class name is followed by an inline body that overrides callback methods.
- Example:
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText("Saved");
}
});- Lambda comparison: Functional interfaces such as
ActionListenermay use lambdas, but multi-method interfaces such asMouseListenercannot be represented directly by one lambda.
B. Listener interface adapter
A listener interface adapter is an abstract convenience class that supplies empty implementations of every method in a multi-method listener interface.
- Purpose: A subclass overrides only the callbacks it needs instead of implementing every interface method.
- Common adapters:
MouseAdapter,KeyAdapter,WindowAdapter, andFocusAdapter. - Contrast:
- Implementing
MouseListenerrequires all five callback methods. - Extending
MouseAdapterpermits overriding onlymouseClicked, for example.
- Implementing
- Limitation: Because Java supports single class inheritance, a class already extending another class may use an anonymous adapter object rather than extending the adapter itself.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →