Chapter 9: Graphics and User Interfaces
Introduction
Learning Outcomes
Create windows and panels with JFrame and JPanel, add components, show and close the window.
Override paintComponent and draw shapes and text with Graphics, using screen coordinates.
Arrange components with BorderLayout, FlowLayout and GridLayout.
Handle mouse and button events with listener interfaces, adapter classes and lambdas.
Explain why the GUI is built on the event thread with SwingUtilities.invokeLater.
Read and modify a drawing program, a text converter and a change calculator.
Graphics Programming
Graphics Programming
- Java offers a powerful, complete toolkit for building graphical user interfaces (GUIs): windows, buttons, text fields, drawings.
- With it you can write interactive, visual applications. Three ideas are key:
The building blocks of the interface: windows, buttons, labels, text fields. Each is an object of some class.
Captures user actions such as mouse clicks and key presses, and calls the methods that respond to them.
Draws shapes, updates the screen and renders the components.
Analogy: a GUI program is like a shop waiting for customers. The window display (components) is set up, then the program waits; whenever a customer touches something (an event), the right clerk (a listener method) steps in.
Graphics Programming
Console vs GUI Programs
| Console program | GUI program | |
|---|---|---|
| Flow | Sequential: main runs top to bottom; the program asks the questions | Event-driven: the program waits for the user's move |
| Input | Lines read from the keyboard with Scanner | Buttons, text fields, mouse; listener methods are called |
| Output | System.out.println | Component text changes or the panel is repainted |
| End | The program ends when main does | Runs until the window closes, even after main returns |
| Library | java.util, java.io | java.awt, javax.swing, java.awt.event |
Rule: in a GUI program, “what happens next?” is decided not by the order of the code but by the user's next action. Most of the code is listeners of the form “when this happens, do that”.
Graphics Programming
AWT and Swing
java.awtJava's first graphics library. Today it is used mostly for its shared classes: Graphics, Color, Font, Point, layout managers and event classes (java.awt.event).
javax.swingBuilt on top of AWT; Java draws the components itself. Class names start with J: JFrame, JPanel, JButton, JLabel…
Hollow triangle: “extends” (inheritance). JFrame is an AWT window; the other Swing components extend JComponent (JButton via AbstractButton).
Graphics Programming
Building a GUI App
- Add components to the interface using Java's graphics classes.
- Define event-handling methods that respond to user actions.
- Render the visuals with methods such as
paint()orpaintComponent().
The screen is a grid of pixels. Coordinates are integers measured from the component's top-left corner. Unlike the axes in math, y grows downward: (0, 0) is the top-left pixel, (getWidth() − 1, getHeight() − 1) the bottom-right one.
Graphics Programming
Basic Graphics Concepts
A surface you can draw on. Swing usually uses a JPanel (AWT has Canvas): we extend JPanel and draw inside it.
Graphics classThe “pen” that does the drawing. Methods: drawLine(), drawRect(), fillOval(), drawString(), drawImage()…
Color and FontColor sets the pen's color and Font its typeface: g.setColor(Color.RED), g.setFont(new Font("Serif", Font.BOLD, 24)).
The pen analogy: the Graphics object is the pen in the programmer's hand. setColor swaps the pen; until you swap it again, everything is drawn in the same color.
Graphics Programming
Drawing with paintComponent
import java.awt.*; import javax.swing.*; class DrawPanel extends JPanel { @Override public void paintComponent(Graphics g) { super.paintComponent(g); // clear background g.setColor(Color.BLUE); g.drawRect(20, 30, 50, 70); // x, y, w, h g.drawString("Hello, Java Graphics!", 100, 100); } }
- We never call
paintComponentourselves: Swing calls it when the window first opens, when it is resized or whenrepaint()is requested, and hands us a readyGraphics g. panel.getGraphics()also returns a graphics object, but anything drawn with it is erased the next time the window repaints. For lasting drawings, usepaintComponent.
Result with a 300 × 160 panel. The y of drawString is the text's baseline (the bottom of the letters).
Graphics Programming
Graphics Drawing Methods
| Method | What it does |
|---|---|
drawLine(x1, y1, x2, y2) | Line between two points |
drawRect(x, y, w, h) | Rectangle outline; (x, y) is the top-left corner |
fillRect(x, y, w, h) | Filled rectangle |
drawOval(x, y, w, h) | Ellipse that fits this rectangle (circle if w = h) |
fillOval(x, y, w, h) | Filled ellipse / circle |
drawString(s, x, y) | Text; y is the baseline |
setColor(c) / setFont(f) | Color / font of later drawings |
drawImage(img, x, y, null) | Draws an image at (x, y) |
Ellipses and circles are given by their bounding rectangle: the top-left corner, not the center. A circle with center (cx, cy) and radius r: fillOval(cx − r, cy − r, 2r, 2r).
Graphics Programming
Shapes: Code and Result
class ShapesPanel extends JPanel { @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.drawLine(10, 10, 110, 60); g.drawRect(130, 10, 80, 50); g.fillRect(230, 10, 80, 50); g.drawOval(10, 80, 100, 60); g.fillOval(130, 80, 60, 60); g.drawString("Hello", 230, 115); } }
With no color set, the pen uses the panel's foreground color (dark gray in Swing). draw… draws outlines, fill… filled shapes.
Drawings are painted on top of each other; later ones cover earlier ones.
Graphics Programming · Step-by-step trace
Shapes: Drawing Order, Step by Step
class ShapesPanel extends JPanel { @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.drawLine(10, 10, 110, 60); g.drawRect(130, 10, 80, 50); g.fillRect(230, 10, 80, 50); g.drawOval(10, 80, 100, 60); g.fillOval(130, 80, 60, 60); g.drawString("Hello", 230, 115); } }
Swing calls this method itself. super.paintComponent(g) clears the canvas with the background color.
A line between two points. Since y grows downward, the line runs right and down.
drawRect: (x, y) is the top-left corner; only the outline is drawn.
fillRect: a rectangle of the same size, filled with the pen color.
drawOval: the ellipse that fits the dashed box. (10, 80) is the box's corner, not the ellipse's.
Width = height, so it is a filled circle: center (160, 110), radius 30.
In drawString, y is the text's baseline: the letters sit above 115.
The method ends; every time the window repaints (resize, repaint()), everything is drawn again from scratch in the same order.
Windows and Panels
The JFrame Class
Creates a top-level window with a title bar and minimize and close buttons. Every other component lives inside a window.
| Code | Purpose |
|---|---|
JFrame frame = new JFrame("Title"); | Creates a window with the given title (not yet visible) |
frame.add(component); | Adds a component to the window (its content pane) |
frame.setSize(400, 300); | Width and height (pixels, borders included) |
frame.pack(); | Sizes the window to its components' preferred sizes |
frame.setLocation(x, y); | Position on screen; setLocationRelativeTo(null) centers it |
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | Ends the program when the window closes |
frame.setVisible(true); | Makes the window visible (usually called last) |
Windows and Panels
A First Window
import javax.swing.JFrame; import javax.swing.SwingUtilities; public class JFrameDemo { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("Java JFrame Example"); frame.setSize(400, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
- The GUI is built on the event thread with
invokeLater(see The Event Thread). - Forget
setVisible(true)and the window exists but stays invisible. - Without
EXIT_ON_CLOSEthe default isHIDE_ON_CLOSE: the window hides, but the program keeps running in the background. - Without a size, the window opens at nearly 0 × 0, just a title bar.
An empty 400 × 300 window (scaled).
Windows and Panels
The JPanel Class
- A container in the
javax.swingpackage: it holds other GUI elements. - Used to group and arrange the components inside a window; nesting several panels builds complex layouts.
- Customize color, border and size with
setBackground(),setBorder(),setPreferredSize(). - The canvas for our own drawings, animations and graphics: extend
JPaneland overridepaintComponent. - Helps split the code up: each panel can be its own class.
Windows and Panels
JPanel Example
import java.awt.Color; import javax.swing.*; public class PanelDemo { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JPanel panel = new JPanel(); panel.setBackground(Color.LIGHT_GRAY); panel.add(new JButton("Click")); JFrame frame = new JFrame("JPanel Example"); frame.add(panel); frame.setSize(300, 150); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); } }
Color.LIGHT_GRAY = (192, 192, 192). The button sits at the top center of the panel.
Why top center? JPanel's default layout manager is FlowLayout: it lays out components at their preferred size, row by row, centered. The JFrame's content pane uses BorderLayout, so the panel fills the whole window.
Drawing Tools · Step-by-step trace
The Point Class: an (x, y) Point
A Point object is created; its fields x and y are public int.
getX() returns a double: 30.0.
getY(): 40.0.
double values print with a decimal point.
Accessing the fields directly gives ints.
Distance to the origin: √(30² + 40²) = 50.0.
setLocation moves the point. The variables keep the old values.
toString() prints the class name and fields.
translate(dx, dy) shifts it relatively. y decreased: the point moved up.
The new position is printed.
static distance(x1, y1, x2, y2): from (0, 0) to (3, 4) is 5.0.
Point p = new Point(30, 40); double px = p.getX(); double py = p.getY(); System.out.println(px + " " + py); System.out.println(p.x + " " + p.y); System.out.println(p.distance(0, 0)); p.setLocation(60, 80); System.out.println(p); p.translate(5, -10); // 5 right, 10 up System.out.println(p); System.out.println(Point.distance(0, 0, 3, 4));
Drawing Tools
The Color Class
- Provides coloring for the interface and drawings (
java.awt.Color). - Predefined constants:
Color.RED,Color.GREEN,Color.WHITE,Color.LIGHT_GRAY… - RGB: red, green and blue components from 0 to 255:
new Color(int red, int green, int blue). darker()multiplies the components by 0.7,brighter()divides them by 0.7 (max 255): each returns a new color object.
Color orange = new Color(255, 128, 0);
System.out.println(orange);
System.out.println(orange.getGreen());
System.out.println(Color.RED.darker());java.awt.Color[r=255,g=128,b=0] 128 java.awt.Color[r=178,g=0,b=0]
Color.RED (255, 0, 0)Color.BLUE (0, 0, 255)Color.LIGHT_GRAY (192, 192, 192)new Color(255, 128, 0) orangeorange.darker() (178, 89, 0)Color.RED.darker() (178, 0, 0)Color.GREEN.darker() (0, 178, 0)new Color(100, 50, 0).brighter() (142, 71, 0)Drawing Tools
The Font Class
Sets the typeface, style and size of text: new Font(name, style, size).
| Parameter | Values |
|---|---|
| name | "Serif", "SansSerif", "Monospaced", "Dialog" (logical names available on every system) or a real font such as "Arial" |
| style | Font.PLAIN (0), Font.BOLD (1), Font.ITALIC (2), or both: Font.BOLD | Font.ITALIC |
| size | Integer point size, e.g. 24 |
public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(new Color(0, 102, 204)); g.setFont(new Font("Serif", Font.BOLD, 24)); g.drawString("Java", 20, 40); g.setFont(new Font("Monospaced", Font.PLAIN, 14)); g.drawString("Swing", 20, 70); }
Components such as JLabel use the same object: label.setFont(f). To derive from an existing font: f.deriveFont(Font.ITALIC, 18f).
Layout Managers
Layout Managers
A layout manager computes the size and position of the components in a container by rule: panel.setLayout(new GridLayout(2, 3));. We use one instead of hard-coding coordinates because the layout is recomputed automatically when the window grows or the font or screen resolution changes.
Left to right; wraps when a row fills. JPanel default.
Five regions. Default for a JFrame's content pane.
A grid of equal cells: new GridLayout(2, 3).
A single row or column: BoxLayout.Y_AXIS.
The more flexible but complex GridBagLayout builds a grid of cells of different sizes. Nesting panels, each with a simple manager, is usually enough.
Layout Managers · Step-by-step trace
How FlowLayout Fills Its Rows
int[] w = {90, 60, 110, 70, 80}; JPanel panel = new JPanel(); // FlowLayout(CENTER, 5, 5) panel.setSize(260, 120); for (int i = 0; i < w.length; i++) { JButton b = new JButton("B" + i); b.setPreferredSize(new Dimension(w[i], 30)); panel.add(b); } panel.doLayout(); // compute positions for (Component c : panel.getComponents()) System.out.println(c.getX() + ", " + c.getY());
JPanel's default manager is FlowLayout: centered, with a 5-pixel gap between components. The dashed lines are the margins.
add only appends the button to a list; its position is still (0, 0), its size 0 × 0.
Loop done: five buttons added, none placed. Placement happens only when the layout is computed.
doLayout(): usable width 260 − 2 × 5 = 250. B0 and B1 fit: 155 pixels.
Adding B2 would make the row 270 pixels: it doesn't fit, so it goes to the next row.
Row 1 is centered: B0 x = 52, B1 x = 52 + 90 + 5 = 147, y = 5.
Row 2: B2 and B3 (185 pixels); adding B4 would make 270. Centering: x0 = 5 + (250 − 185)/2 = 37.
B4 sits alone on row 3; y = 5 + 30 + 5 + 30 + 5 = 75.
The computed bounds are printed. If the panel widens, the rows are recomputed and the buttons move.
Layout Managers
The BorderLayout Class
- Places components in five regions:
NORTH,SOUTH,WEST,EAST,CENTER. - Good for components of different priority: toolbar on top, status bar at the bottom, main content in the middle.
- A component added without a region goes to the center:
add(b)=add(b, BorderLayout.CENTER). - Each region holds one component; adding a second to the same region replaces the first.
- North and south take the full width, west and east the remaining height; the center fills everything left.
setHgap()andsetVgap()set the horizontal and vertical gaps between regions (pixels).
Layout Managers · Step-by-step trace
BorderLayout: Filling the Regions
The panel will use BorderLayout with 5-pixel gaps between regions. No components yet.
The North button takes the full width; its height is the button's preferred height.
South also spans the full width, at the bottom.
West takes the height between north and south; its width fits its text.
East goes to the right edge.
Center fills all the remaining space. When the window grows, the center grows most.
JPanel panel = new JPanel(); BorderLayout layout = new BorderLayout(); layout.setHgap(5); layout.setVgap(5); panel.setLayout(layout); panel.add(new JButton("North"), BorderLayout.NORTH); panel.add(new JButton("South"), BorderLayout.SOUTH); panel.add(new JButton("West"), BorderLayout.WEST); panel.add(new JButton("East"), BorderLayout.EAST); panel.add(new JButton("Center"), BorderLayout.CENTER);
No Entry Sign
No Entry Sign
Goal: a panel that draws the “no entry” traffic sign. The shape is four layers painted on top of each other:
- Green background (
setBackground) - Large white circle (outer ring)
- Slightly smaller red circle
- White horizontal bar in the middle
Every measurement is computed from getWidth() and getHeight(): when the window grows, the sign grows too and stays centered.
No Entry Sign
The paintComponent Code
public class NoEntrySign extends JPanel { @Override public void paintComponent(Graphics g) { super.paintComponent(g); var c = new Point(getWidth() / 2, getHeight() / 2); // center var r = Math.min(getWidth() / 2, getHeight() / 2) - 5; // radius var r2 = (int) (r * 0.9); // inner radius var bw = (int) (r2 * 1.4); // bar width var bh = (int) (r2 * 0.35); // bar height g.setColor(Color.WHITE); g.fillOval(c.x - r, c.y - r, 2 * r, 2 * r); g.setColor(Color.RED); g.fillOval(c.x - r2, c.y - r2, r2 * 2, r2 * 2); g.setColor(Color.WHITE); g.fillRect(c.x - bw / 2, c.y - bh / 2, bw, bh); } }
var (Java 10+): the compiler infers the type from the right-hand side; here c is a Point, the others int. Classic form: Point c = new Point(…); int r = …;. The (int) cast drops the fractional part. Imports needed: java.awt.* and javax.swing.*.
No Entry Sign · Step-by-step trace
Drawing the Sign: Tracing paintComponent
The panel is 384 × 261 pixels. super.paintComponent paints the background color (green).
Center: (384 / 2, 261 / 2) = (192, 130). Integer division: 130.5 → 130.
Radius: min(192, 130) − 5 = 125. Based on the shorter side, with a 5-pixel margin.
Inner radius: (int) 112.5 = 112.
Bar width: (int) (112 × 1.4) = (int) 156.8 = 156.
Bar height: (int) 39.2 = 39.
fillOval(67, 5, 250, 250): the white circle; its bounding square is dashed.
fillOval(80, 18, 224, 224): the red circle is painted over the white one, leaving a 13-pixel white ring.
fillRect(114, 111, 156, 39): the white bar goes on top. The sign is done.
super.paintComponent(g); var c = new Point(getWidth() / 2, getHeight() / 2); var r = Math.min(getWidth() / 2, getHeight() / 2) - 5; var r2 = (int) (r * 0.9); var bw = (int) (r2 * 1.4); var bh = (int) (r2 * 0.35); g.setColor(Color.WHITE); g.fillOval(c.x - r, c.y - r, 2 * r, 2 * r); g.setColor(Color.RED); g.fillOval(c.x - r2, c.y - r2, r2 * 2, r2 * 2); g.setColor(Color.WHITE); g.fillRect(c.x - bw / 2, c.y - bh / 2, bw, bh);
No Entry Sign
main and the Window
public static void main(String[] args) { SwingUtilities.invokeLater(() -> { var panel = new NoEntrySign(); panel.setBackground(Color.GREEN.darker()); var frame = new JFrame("A simple graphics program"); frame.setSize(400, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(panel, BorderLayout.CENTER); frame.setVisible(true); }); }
SwingUtilities.invokeLater(() -> { … })builds the GUI on the event thread.() -> { … }is a lambda expression (Java 8+): “a piece of code to run later”.Color.GREEN.darker()= (0, 178, 0): a bit darker than pure green.- The panel is added to the center of the content pane; as the only component, it fills the whole area.
- In a 400 × 300 window, minus the borders and title bar, the panel is about 384 × 261 (varies by OS).
Mouse Events
Interactive Computer Graphics
- Computer graphics is the creation and processing of visual content. In interactive graphics the user changes the image with input devices such as the mouse and keyboard: drawing programs, games, maps.
- Graphics libraries draw, color and transform graphical objects; interaction happens through the event loop below.
A listener doesn't paint the screen directly: it updates the data and requests a repaint with repaint(). Swing calls paintComponent at the right moment.
Mouse Events
Listener Interface and Adapter
Interface: all five methods must be written
class ClickListener implements MouseListener { public void mouseClicked(MouseEvent e) { System.out.println("click"); } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } }
MouseAdapter: override only what you need
class ClickListener extends MouseAdapter { @Override public void mouseClicked(MouseEvent e) { System.out.println("click"); } } // panel.addMouseListener(new ClickListener());
MouseAdapteris a ready-made class that implementsMouseListener(andMouseMotionListener,MouseWheelListener) with empty bodies. A subclass writes only the method it cares about.- Motion events live in a separate interface:
MouseMotionListener(mouseDragged,mouseMoved); its adapter isMouseMotionAdapter. Register withaddMouseListener(…),addMouseMotionListener(…). - The
new MouseAdapter() { … }form is an anonymous inner class: a nameless, single-use subclass.
Mouse Events
Mouse Event Methods
| Method | Interface | When is it called? |
|---|---|---|
mousePressed(e) | MouseListener | The moment a mouse button is pressed |
mouseReleased(e) | MouseListener | When the button is released |
mouseClicked(e) | MouseListener | Press and release in the same spot (pressed → released → clicked) |
mouseEntered(e) / mouseExited(e) | MouseListener | The pointer enters / leaves the component |
mouseMoved(e) | MouseMotionListener | Moving with no button pressed |
mouseDragged(e) | MouseMotionListener | Moving with a button held down (dragging) |
mouseWheelMoved(e) | MouseWheelListener | The wheel is turned |
Every method takes a MouseEvent e: it tells where, with which button and with which keys held the event happened.
Mouse Events
The MouseEvent Class
| Method | Returns |
|---|---|
getX(), getY() | Pointer position relative to the component |
getPoint() | The same position as a Point |
getButton() | BUTTON1 left, BUTTON2 middle, BUTTON3 right |
getClickCount() | Number of consecutive clicks (2: double-click) |
isShiftDown(), isCtrlDown(), isAltDown() | Is the key held down right now? |
panel.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { String button = "left"; if (e.getButton() == MouseEvent.BUTTON3) { button = "right"; } System.out.println(button + " (" + e.getX() + ", " + e.getY() + ")" + (e.isShiftDown() ? " + Shift" : "")); } });
Represents the state after a mouse event. Coordinates are relative to the component, not the screen: the panel's top-left corner is (0, 0).
Mouse Events
Mouse Events Playground
Java call and MouseEvent values
(no events yet)
Browser events are shown as their Java counterparts. A click fires three events: pressed → released → clicked; a drag fires many mouseDragged events. A right click is BUTTON3.
Mouse Events
SwingUtilities and the Event Thread
javax.swing.SwingUtilitiesholds helper methods.- Swing components are not thread-safe: if several threads touch them at once, they can become inconsistent.
- Rule: components are created and modified only on the Event Dispatch Thread (EDT). Listener methods already run on the EDT.
- Analogy: the kitchen has a single cook (the EDT); everyone else leaves an order ticket (a
Runnable) instead of cooking.
| Method | Behavior |
|---|---|
invokeLater(task) | Queues the task and returns immediately (asynchronous). The standard way to start a GUI. |
invokeAndWait(task) | Waits until the task finishes on the EDT (synchronous). Called from the EDT itself, it throws an Error (the EDT can't wait for itself). |
Mouse Events · Step-by-step trace
The Event Queue: invokeLater and invokeAndWait
public static void main(String[] a) throws Exception { System.out.println("1 main"); SwingUtilities.invokeLater( () -> System.out.println("3 task A")); SwingUtilities.invokeLater( () -> System.out.println("4 task B")); System.out.println("2 main goes on"); SwingUtilities.invokeAndWait(() -> System.out.println( "5 task C, EDT? " + SwingUtilities.isEventDispatchThread())); System.out.println("6 main, EDT? " + SwingUtilities.isEventDispatchThread()); }
The program starts on the main thread. The event thread (EDT) doesn't exist yet.
invokeLater queues task A and returns at once. The EDT starts.
Task B is queued too; main still doesn't wait.
main carries on. (In this run the EDT hasn't picked up a task yet; the two threads are independent.)
invokeAndWait queues task C and blocks main.
The EDT runs task A from the head of the queue (the thread is named AWT-EventQueue-0).
Order is preserved: task B runs after task A.
Task C also runs on the EDT (true). When it finishes, the waiting main wakes up.
main is not the EDT (false). That's why components are touched only from the EDT.
Drawing Program
A Simple Drawing Program
curves.size() = 0, total points = 0A program for drawing by holding down the mouse button and dragging.
- On press (
mousePressed) a new curve starts. - While dragging (
mouseDragged) points are appended to the curve and arepaintis requested. - When painting (
paintComponent) the consecutive points of each curve are joined with lines.
The program stores the drawing not as an image but as lists of points; the screen is redrawn from this data every time.
Drawing Program
Storing the Curves
public class BasitDrawPanel extends JPanel { private List<List<Point>> curves = new ArrayList<>(); public BasitDrawPanel() { addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { var curve = new ArrayList<Point>(); curve.add(new Point(e.getX(), e.getY())); curves.add(curve); } }); addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { curves.get(curves.size() - 1) .add(new Point(e.getX(), e.getY())); repaint(0, 0, getWidth(), getHeight()); } }); } }
List<List<Point>>: a list of lists. The outer list holds the curves; each inner list holds one curve's points.- The last curve:
curves.get(curves.size() - 1). The last index issize() - 1;get(size())throwsIndexOutOfBoundsException.
Drawing Program · Step-by-step trace
Tracing the Mouse Events
mousePressed: pressed at (40, 120): a new inner list is created, gets its first point and goes into the outer list.
mouseDragged: dragged to (60, 60): a point is added to the last curve; repaint requests a redraw and the line appears.
mouseDragged: dragged to (80, 120): the same curve grows. In reality dozens of mouseDragged events arrive per second.
mouseReleased: released. We didn't write mouseReleased, so MouseAdapter's empty body runs and nothing happens.
mousePressed: pressed again at (50, 95): a second curve starts. The old curve stays as it is.
mouseDragged: dragged to (70, 95): the point again goes to the last curve, curve 1.
addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { var curve = new ArrayList<Point>(); curve.add(new Point(e.getX(), e.getY())); curves.add(curve); } }); addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { curves.get(curves.size() - 1) .add(new Point(e.getX(), e.getY())); repaint(0, 0, getWidth(), getHeight()); } });
Drawing Program · Step-by-step trace
Drawing the Curves: paintComponent
The background is cleared; nothing of the previous drawing remains.
The first curve; prev is its first point.
The inner loop starts at the first point: it joins itself, so a single pixel is drawn. Then prev = p.
The line (40,120) → (60,60).
(60,60) → (80,120). Curve 0 is done.
The outer loop moves to the second curve; prev is reset to its first point, so the two curves are not joined.
Again a single pixel.
(50,95) → (70,95). Five drawLine calls complete the drawing.
@Override public void paintComponent(Graphics g) { super.paintComponent(g); for (var c : curves) { var prev = c.get(0); for (var p : c) { g.drawLine(prev.x, prev.y, p.x, p.y); prev = p; } } }
Drawing Program
main and repaint
public static void main(String[] args) { SwingUtilities.invokeLater(() -> { var frame = new JFrame("Simple Drawing Program"); frame.getContentPane().add(new BasitDrawPanel(), BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 300); frame.setVisible(true); }); }
repaint()does not draw right away: it queues a “repaint” request. Back-to-back requests may be merged.repaint(x, y, w, h)asks to redraw only that rectangle. Swing clips everything else:gcan't paint outside the region, so there is less work.repaint(0, 0, getWidth(), getHeight())=repaint().- Forget
super.paintComponent(g)and the background isn't cleared; leftovers of the old image may remain. - We never call
paintComponentourselves; we change the data and requestrepaint().
Text Components
The JButton Class
- Creates clickable buttons, customized with text, icons and event handlers.
setText()sets the text,setIcon()the icon;setEnabled(false)disables it.addActionListener()adds a listener that runs on click (ActionListener, whose single method isactionPerformed). Adding listeners is the Observer pattern: the button is the subject, the listeners are observers.
class CounterPanel extends JPanel { private int count = 0; private JLabel label = new JLabel("Not clicked yet"); CounterPanel() { JButton button = new JButton("Click"); button.addActionListener(e -> { count++; label.setText(count + " click(s)"); }); add(button); add(label); } }
Text Components · Step-by-step trace
Counter Button: A Click, Step by Step
class CounterPanel extends JPanel { private int count = 0; private JLabel label = new JLabel("Not clicked yet"); CounterPanel() { JButton button = new JButton("Click"); button.addActionListener(e -> { count++; label.setText(count + " click(s)"); }); add(button); add(label); } }
As the object is created, its fields are initialized first: count is 0, the label is ready.
The constructor creates a button; button is a local variable.
The lambda is not run, only registered with the button. Its body will run on a click.
The button and label are added to the panel (FlowLayout: side by side). The constructor ends.
The user clicks: the EDT calls actionPerformed, the lambda body. count is a field, so it can be incremented.
setText changes the label's text; Swing repaints the label.
Second click: the same lambda is called again; the field becomes 2.
The label updates. Between clicks the program runs no code at all; it just waits for events.
Text Components
ActionListener: Anonymous Class and Lambda
Anonymous inner class (classic)
button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { count++; label.setText("Count: " + count); } });
Lambda expression (Java 8+)
button.addActionListener(e -> {
count++;
label.setText("Count: " + count);
});
// one expression: no braces needed
button.addActionListener(e -> System.exit(0));ActionListenerhas just one abstract method (a functional interface), so the compiler accepts the lambdae -> …as the body ofactionPerformed.MouseListenerhas five methods, so it can't be a lambda; use an adapter class there.- A lambda cannot modify a local variable:
int count = 0; … e -> count++won't compile. Mutable values such as counters must be fields.
Text Components
JLabel and JTextField
JLabel: a labelDisplays text or an image; the user can't change it.
setText() sets the text, setIcon() the image, setFont() the font, setForeground() the text color.
JTextField: a one-line text fieldLets the user enter text; forms collect data with it.
getText() / setText() read and write, setColumns() sets the visible width in columns, addActionListener() fires on Enter.
JLabel label = new JLabel("Your name:"); label.setFont(new Font("SansSerif", Font.BOLD, 14)); label.setForeground(Color.BLUE); JTextField nameField = new JTextField(12); JLabel greeting = new JLabel(" "); nameField.addActionListener(e -> greeting.setText( "Hello, " + nameField.getText() + "!"));
Text Components
JTextArea and JScrollPane
JTextArea: multi-line textContent can be read, set and updated. new JTextArea(rows, cols) fixes the visible size up front. getText(), setText(), append() (add at the end), setEditable(false) (read-only), setLineWrap(true) (wrap lines).
JScrollPane: a scroll paneWhen the component inside (text area, table, image) doesn't fit, it adds scroll bars automatically and adapts as the content changes size. Set its size with setPreferredSize(), its content with setViewportView().
JTextArea area = new JTextArea(5, 20); area.setText("First line\n"); area.append("Second line\n"); JScrollPane scroll = new JScrollPane(area); System.out.print(area.getText()); System.out.println(area.getLineCount());
First line Second line 3
Case Converter
Text Converter: The Window
- In the
CENTER, an 8-row × 50-columnJTextAreainside aJScrollPane. - At the bottom (
SOUTH), aJPanelholding two buttons (FlowLayout: centered). pack()computes the window size from these components' preferred sizes.- The buttons convert the text with
toLowerCase()/toUpperCase()and write it back.
Note: toUpperCase() uses the machine's locale. On an English-locale machine "istanbul" → "ISTANBUL"; on a Turkish one, "İSTANBUL". To pin the result: toUpperCase(Locale.ROOT) or toUpperCase(Locale.forLanguageTag("tr")). This demo uses English rules.
Case Converter
Text Converter: The Code
import java.awt.BorderLayout; import javax.swing.*; public class CaseConverter { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { var area = new JTextArea("Java Programming", 8, 50); var lowerButton = new JButton("To Lowercase"); var upperButton = new JButton("To Uppercase"); lowerButton.addActionListener(e -> area.setText(area.getText().toLowerCase())); upperButton.addActionListener(e -> area.setText(area.getText().toUpperCase())); var panel = new JPanel(); panel.add(lowerButton); panel.add(upperButton); var frame = new JFrame("CaseConverter"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new JScrollPane(area), BorderLayout.CENTER); frame.getContentPane().add(panel, BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); }); } }
- The whole GUI is built inside one lambda, on the EDT.
areais a local variable, but the lambda only reads it (never reassigns it), so it may use it (effectively final).toUpperCase()returns a newString; sinceStringis immutable, the result must be written back withsetText.- Write
BorderLayout.CENTERin full; a bareCENTERwon't compile.
Case Converter
What Happens on a Click?
The user clicks “To Uppercase”; the operating system passes this to Java.
Java creates an event object and puts it on the event queue.
The EDT takes the next event; the button calls actionPerformed on every registered ActionListener, so our lambda runs.
area.getText() reads the current text.
toUpperCase() makes a new string; the old one is unchanged.
setText updates the area's model; the area repaints itself with repaint. The EDT moves on to the next event.
Change Calculator
Making Change
Shows how to pay the amount entered (in cents) with the fewest coins (50, 25, 10, 5, 1).
- There is no button: the report updates by itself on every keystroke.
- A
DocumentListenerattached to the text field's document (Document) makes this happen. - Try: 93, 287, an empty field,
abc,-7.
Change Calculator
Fields and Constructor
public class ChangeCalculator extends JFrame { private JTextField amountField = new JTextField(12); private Document doc = amountField.getDocument(); private JTextArea report = new JTextArea(8, 40); public ChangeCalculator() { var topPanel = new JPanel(); topPanel.add(new JLabel("Amount:")); topPanel.add(amountField); getContentPane().add(topPanel, BorderLayout.NORTH); getContentPane().add(new JScrollPane(report), BorderLayout.CENTER); setBackground(Color.LIGHT_GRAY); report.setEditable(false); doc.addDocumentListener(new DocumentListener() { public void insertUpdate(DocumentEvent e) { updateReport(); } public void removeUpdate(DocumentEvent e) { updateReport(); } public void changedUpdate(DocumentEvent e) { updateReport(); } }); }
- The class extends
JFrame. Swing separates data from display (MVC): theJTextFieldis the view; theDocumentfromgetDocument()is the model holding the text. DocumentListener:insertUpdate(text added),removeUpdate(removed),changedUpdate(style changed; never called for plain text). It is an interface, so all three are written.
Change Calculator · Step-by-step trace
updateReport: 93 cents
The field's text "93" is read and parsed as an integer.
The coin values, largest first, in an array.
setText starts the report from scratch: old content is erased.
x = 50: 93 / 50 = 1 (integer division); the line is appended.
Left: 93 % 50 = 43.
x = 25: 43 / 25 = 1 (integer division); the line is appended.
Left: 43 % 25 = 18.
x = 10: 18 / 10 = 1 (integer division); the line is appended.
Left: 18 % 10 = 8.
x = 5: 8 / 5 = 1 (integer division); the line is appended.
Left: 8 % 5 = 3.
x = 1: 3 / 1 = 3 (integer division); the line is appended.
Left: 3 % 1 = 0.
void updateReport() { try { var amount = Integer.parseInt( doc.getText(0, doc.getLength())); int[] coins = {50, 25, 10, 5, 1}; report.setText(amount + " cents in coins:\n"); for (int x : coins) { report.append(amount / x + " x " + x + "c\n"); amount %= x; } } catch (NumberFormatException e) { report.setText("Not an integer or out of range"); } catch (Exception e) { report.setText(e.toString()); } }
Change Calculator
main and the Order of Events
public static void main(String[] args) { SwingUtilities.invokeLater(() -> { var frame = new ChangeCalculator(); frame.setTitle("Change Calculator"); frame.pack(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); }
| User / code | Event → report |
|---|---|
types 9 | insertUpdate → 9 cents: 1 × 5, 4 × 1 |
types 3 | insertUpdate → the 93-cent report |
| deletes it all | removeUpdate → parseInt(""): “Not an integer…” |
abc or 99999999999 | NumberFormatException → same message |
setText("287") | two events: first removeUpdate, then insertUpdate → 5, 1, 1, 0, 2 |
-7 | A valid number! 0, 0, 0, −1, −2: a check is missing |
The first catch handles the expected error (non-numeric text, a value beyond the int range). The second is a general safety net; it is needed because getText(0, n) can throw the checked BadLocationException.
Summary
Good Practices
Don't hard-code coordinates; with a layout manager the layout survives different screen sizes and resolutions.
upperButton, amountField instead of b1, t2: code with dozens of components stays readable.
Design around “what should happen when the user does this?”; one listener per action.
Keep rules such as making change in a separate method or class; it can be tested without a GUI and reused in another one.
The body of main: SwingUtilities.invokeLater(() -> { … }).
A long job in a listener (a download, a big computation) freezes the window; move such work to a separate thread.
Summary
Summary
| Concept | Essence |
|---|---|
| Packages | java.awt: Graphics, Color, Font, Point, layouts, events · javax.swing: the J… components |
JFrame | The window: setSize/pack, setDefaultCloseOperation(EXIT_ON_CLOSE), setVisible(true) last |
JPanel | Container and canvas; FlowLayout by default |
| Drawing | Override paintComponent(Graphics g), call super.paintComponent(g) first; repaint() on changes |
| Coordinates | (0, 0) top left; x right, y down; ovals are given by their bounding rectangle |
| Layout | BorderLayout (5 regions, content-pane default), FlowLayout, GridLayout, BoxLayout |
| Events | Listener interface + add…Listener; adapters for multi-method interfaces; lambdas for single-method ones |
| Mouse | MouseListener, MouseMotionListener; MouseEvent: getX, getY, getButton |
| EDT | Swing is single-threaded; invokeLater is asynchronous, invokeAndWait synchronous |
| Text | JLabel displays, JTextField one line, JTextArea many lines, JScrollPane scrolls |
Summary
Common Mistakes
Without import javax.swing.*; for JFrame: cannot find symbol … class JFrame.
The window never appears, or the program keeps running in the background after it closes.
paintcomponent is a new method that is never called. With @Override: method does not override or implement a method from a supertype.
The background isn't cleared; leftovers of old drawings stay on screen.
ClickListener is not abstract and does not override abstract method mouseExited(MouseEvent) in MouseListener. Fix: MouseAdapter.
IndexOutOfBoundsException: Index 1 out of bounds for length 1. The last element is size() - 1.
e -> count++: local variables referenced from a lambda expression must be final or effectively final. Fix: make the counter a field.
add(comp, CENTER): cannot find symbol … variable CENTER. Use BorderLayout.CENTER.
Summary
Practice Problems
- If the no-entry-sign panel were 200 × 100 pixels, what would
r,r2,bw,bhbe? - What report does the change program show for
68? - Where is the center of the ellipse drawn by
g.drawOval(50, 50, 100, 60)? - In a panel with
BorderLayout, buttonAand then buttonBare added to the sameNORTHregion. Which one shows in the north? - If the user clicks the panel once and releases, which
MouseListenermethods are called, in what order? - What color does
Color.RED.brighter()give?
Show answers
r= min(100, 50) − 5 = 45,r2= (int) 40.5 = 40,bw= 56,bh= 14.- “68 cents in coins:” followed by 1 x 50c, 0 x 25c, 1 x 10c, 1 x 5c, 3 x 1c.
- (50 + 100/2, 50 + 60/2) = (100, 80).
- B: each region holds one component and the last one added wins (A stays in the panel but takes no part in the layout).
mousePressed→mouseReleased→mouseClicked(plusmouseEnteredas the pointer enters the panel).- Still (255, 0, 0): red is already at its brightest, and the green and blue components stay 0.
Summary
Exercises
- Target: draw 5 nested red and white rings that scale with the panel size.
- Counter window: “−1”, “+1” and “Reset” buttons and a
JLabelshowing the value. - Add a “Clear” button to the drawing program.
- In the drawing program, make a right click delete the last curve.
- Make the change program print “Amount must be positive” for negative amounts.
- Temperature converter: enter °C in a
JTextField; a button shows °F.
Answers / hints
- Loop:
int ri = r - i * r / 5;g.setColor(i % 2 == 0 ? Color.RED : Color.WHITE);g.fillOval(cx - ri, cy - ri, 2 * ri, 2 * ri);Draw from largest to smallest. - A field
private static int count;;plus.addActionListener(e -> label.setText("" + (++count)));, panel withFlowLayout. - Button listener:
curves.clear(); repaint();(panel and button in CENTER and SOUTH of aBorderLayout). - At the start of
mousePressed:if (e.getButton() == MouseEvent.BUTTON3) { if (!curves.isEmpty()) curves.remove(curves.size() - 1); repaint(); return; }; at the start ofmouseDragged:if (!SwingUtilities.isLeftMouseButton(e)) return; - After
parseInt:if (amount < 0) { report.setText("Amount must be positive"); return; } double c = Double.parseDouble(field.getText()); result.setText(c * 9 / 5 + 32 + " °F");100 → 212.0 °F; catchNumberFormatExceptionfor bad input.
Summary
References
- Oracle, The Java Tutorials: Creating a GUI With Swing; Performing Custom Painting; Laying Out Components Within a Container; Writing Event Listeners; Concurrency in Swing.
- Oracle, Java SE 21 API Documentation:
java.awt.Graphics,java.awt.Color,javax.swing.JFrame,javax.swing.SwingUtilities. - P. Deitel and H. Deitel, Java: How to Program, 11th ed., Pearson (online chapters: Swing GUI Components; Graphics and Java 2D).
- K. Sierra, B. Bates and T. Gee, Head First Java, 3rd ed., O'Reilly (Chapters 14–15: GUI, Swing and events).
- C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson (Chapters 10–11: graphics programming, event handling, Swing).
- A. B. Downey and C. Mayfield, Think Java, 2nd ed., O'Reilly (Appendix C: Graphics).