Chapter 9: Graphics and User Interfaces

Object Oriented Programming with Java
Graphics programmingJFrame and JPanelDrawing with GraphicsPoint, Color, Font Layout managersMouse eventsButtons and text componentsSample apps
Sercan KÜLCÜ · Giresun University · Computer Engineering

Introduction

Learning Outcomes

Build a window

Create windows and panels with JFrame and JPanel, add components, show and close the window.

Draw

Override paintComponent and draw shapes and text with Graphics, using screen coordinates.

Lay out

Arrange components with BorderLayout, FlowLayout and GridLayout.

Respond to events

Handle mouse and button events with listener interfaces, adapter classes and lambdas.

Start up safely

Explain why the GUI is built on the event thread with SwingUtilities.invokeLater.

Write applications

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:
Components

The building blocks of the interface: windows, buttons, labels, text fields. Each is an object of some class.

Event handling

Captures user actions such as mouse clicks and key presses, and calls the methods that respond to them.

Painting

Draws shapes, updates the screen and renders the components.

build componentswait for eventevent occurslistener runswhen done, goes back to waitingclick, key, mouseactionPerformed…

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 programGUI program
FlowSequential: main runs top to bottom; the program asks the questionsEvent-driven: the program waits for the user's move
InputLines read from the keyboard with ScannerButtons, text fields, mouse; listener methods are called
OutputSystem.out.printlnComponent text changes or the panel is repainted
EndThe program ends when main doesRuns until the window closes, even after main returns
Libraryjava.util, java.iojava.awt, javax.swing, java.awt.event
console:GUI:main startsaskScanner waitscomputemain endsmain: buildEDT waitsevent → listeneruntil window closes

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

AWT (Abstract Window Toolkit), java.awt

Java'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).

Swing, javax.swing

Built on top of AWT; Java draws the components itself. Class names start with J: JFrame, JPanel, JButton, JLabel…

ComponentContainerWindowJComponentFrameJFrameJPanelJButtonJLabelJScrollPaneJTextComponentJTextFieldJTextAreajava.awtjavax.swing

Hollow triangle: “extends” (inheritance). JFrame is an AWT window; the other Swing components extend JComponent (JButton via AbstractButton).

Graphics Programming

Building a GUI App

  1. Add components to the interface using Java's graphics classes.
  2. Define event-handling methods that respond to user actions.
  3. Render the visuals with methods such as paint() or paintComponent().
x = 0x = getWidth()y = 0y = getHeight()(0, 0) top-left cornerx grows right, y grows DOWN

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

Canvas

A surface you can draw on. Swing usually uses a JPanel (AWT has Canvas): we extend JPanel and draw inside it.

The Graphics class

The “pen” that does the drawing. Methods: drawLine(), drawRect(), fillOval(), drawString(), drawImage()…

Color and Font

Color sets the pen's color and Font its typeface: g.setColor(Color.RED), g.setFont(new Font("Serif", Font.BOLD, 24)).

JFrame (window)JPanel: canvasHelloGraphics gsetColor / setFont: change the penfillRect, drawOval, drawString

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 paintComponent ourselves: Swing calls it when the window first opens, when it is resized or when repaint() is requested, and hands us a ready Graphics g.
  • panel.getGraphics() also returns a graphics object, but anything drawn with it is erased the next time the window repaints. For lasting drawings, use paintComponent.
DrawPanel
Hello, Java Graphics!

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

MethodWhat 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)
(40, 40)width 16090

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);
    }
}
ShapesPanel
Hello

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);
    }
}
(0, 0)x →

Swing calls this method itself. super.paintComponent(g) clears the canvas with the background color.

(0, 0)x →(10, 10)(110, 60)

A line between two points. Since y grows downward, the line runs right and down.

(0, 0)x →(130, 10)

drawRect: (x, y) is the top-left corner; only the outline is drawn.

(0, 0)x →(230, 10)

fillRect: a rectangle of the same size, filled with the pen color.

(0, 0)x →(10, 80)

drawOval: the ellipse that fits the dashed box. (10, 80) is the box's corner, not the ellipse's.

(0, 0)x →(130, 80)

Width = height, so it is a filled circle: center (160, 110), radius 30.

(0, 0)x →Hellobaseline y=115

In drawString, y is the text's baseline: the letters sit above 115.

(0, 0)x →Hellobaseline y=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.

CodePurpose
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_CLOSE the default is HIDE_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.
Java JFrame Example

An empty 400 × 300 window (scaled).

Windows and Panels

The JPanel Class

  • A container in the javax.swing package: 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 JPanel and override paintComponent.
  • Helps split the code up: each panel can be its own class.
JFrameframecontent panegetContentPane()JPanelpanelJButtonbuttonJLabellabelJPanelinner panel

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);
        });
    }
}
JPanel Example
Click

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

(0, 0)(30, 40)

A Point object is created; its fields x and y are public int.

(0, 0)(30, 40)

getX() returns a double: 30.0.

(0, 0)(30, 40)

getY(): 40.0.

(0, 0)(30, 40)

double values print with a decimal point.

(0, 0)(30, 40)

Accessing the fields directly gives ints.

(0, 0)(30, 40)

Distance to the origin: √(30² + 40²) = 50.0.

(0, 0)(60, 80)

setLocation moves the point. The variables keep the old values.

(0, 0)(60, 80)

toString() prints the class name and fields.

(0, 0)(65, 70)

translate(dx, dy) shifts it relatively. y decreased: the point moved up.

(0, 0)(65, 70)

The new position is printed.

(0, 0)(65, 70)

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).

ParameterValues
name"Serif", "SansSerif", "Monospaced", "Dialog" (logical names available on every system) or a real font such as "Arial"
styleFont.PLAIN (0), Font.BOLD (1), Font.ITALIC (2), or both: Font.BOLD | Font.ITALIC
sizeInteger 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);
}
TextPanel
JavaSwing

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.

FlowLayout1234

Left to right; wraps when a row fills. JPanel default.

BorderLayoutNSWECENTER

Five regions. Default for a JFrame's content pane.

GridLayout123456

A grid of equal cells: new GridLayout(2, 3).

BoxLayout123

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());
panel 260 × 120added:

JPanel's default manager is FlowLayout: centered, with a 5-pixel gap between components. The dashed lines are the margins.

panel 260 × 120added:B0 90

add only appends the button to a list; its position is still (0, 0), its size 0 × 0.

panel 260 × 120added:B0 90B1 60B2 110B3 70B4 80

Loop done: five buttons added, none placed. Placement happens only when the layout is computed.

panel 260 × 120added:B0 90B1 60B2 110B3 70B4 80

doLayout(): usable width 260 − 2 × 5 = 250. B0 and B1 fit: 155 pixels.

panel 260 × 120B2?added:B0 90B1 60B2 110B3 70B4 80

Adding B2 would make the row 270 pixels: it doesn't fit, so it goes to the next row.

panel 260 × 120B0B1added:B0 90B1 60B2 110B3 70B4 80

Row 1 is centered: B0 x = 52, B1 x = 52 + 90 + 5 = 147, y = 5.

panel 260 × 120B0B1B2B3added:B0 90B1 60B2 110B3 70B4 80

Row 2: B2 and B3 (185 pixels); adding B4 would make 270. Centering: x0 = 5 + (250 − 185)/2 = 37.

panel 260 × 120B0B1B2B3B4added:B0 90B1 60B2 110B3 70B4 80

B4 sits alone on row 3; y = 5 + 30 + 5 + 30 + 5 = 75.

panel 260 × 120B0B1B2B3B4added:B0 90B1 60B2 110B3 70B4 80

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() and setVgap() set the horizontal and vertical gaps between regions (pixels).
NORTHSOUTHWESTEASTCENTER(remaining space)

Layout Managers · Step-by-step trace

BorderLayout: Filling the Regions

BorderLayout
CENTER empty

The panel will use BorderLayout with 5-pixel gaps between regions. No components yet.

BorderLayout
NorthCENTER empty

The North button takes the full width; its height is the button's preferred height.

BorderLayout
NorthSouthCENTER empty

South also spans the full width, at the bottom.

BorderLayout
NorthSouthWestCENTER empty

West takes the height between north and south; its width fits its text.

BorderLayout
NorthSouthWestEastCENTER empty

East goes to the right edge.

BorderLayout
NorthSouthWestEastCenter

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:

  1. Green background (setBackground)
  2. Large white circle (outer ring)
  3. Slightly smaller red circle
  4. 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.

A simple graphics program

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.
Usermouse, keyboardOperating systeminput device signalEvent queueMouseEvent, KeyEvent…Event thread(EDT) takes the next eventListener methodmousePressed(e)…repaint()repaint requestpaintComponent(g)called by SwingScreenupdated imagenext event

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());
  • MouseAdapter is a ready-made class that implements MouseListener (and MouseMotionListener, 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 is MouseMotionAdapter. Register with addMouseListener(…), addMouseMotionListener(…).
  • The new MouseAdapter() { … } form is an anonymous inner class: a nameless, single-use subclass.

Mouse Events

Mouse Event Methods

MethodInterfaceWhen is it called?
mousePressed(e)MouseListenerThe moment a mouse button is pressed
mouseReleased(e)MouseListenerWhen the button is released
mouseClicked(e)MouseListenerPress and release in the same spot (pressed → released → clicked)
mouseEntered(e) / mouseExited(e)MouseListenerThe pointer enters / leaves the component
mouseMoved(e)MouseMotionListenerMoving with no button pressed
mouseDragged(e)MouseMotionListenerMoving with a button held down (dragging)
mouseWheelMoved(e)MouseWheelListenerThe wheel is turned
click:mouseEnteredmousePressedmouseReleasedmouseClickedmouseExiteddrag: mousePressed → mouseDragged … → mouseReleased; the pointer moved, so no mouseClicked

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

MethodReturns
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

Mouse Events
Clicking and dragging on the panel fire events (also with Shift or Ctrl held).

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.SwingUtilities holds 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.
main threadmain endsinvokeLater(task)event queuetaskmousekeypaintevent thread (EDT)runs them one at a timelasts until the window closes
MethodBehavior
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());
}
mainevent queueEDTrunningfirst in, first outnone

The program starts on the main thread. The event thread (EDT) doesn't exist yet.

mainevent queueEDTrunningAfirst in, first outempty

invokeLater queues task A and returns at once. The EDT starts.

mainevent queueEDTrunningABfirst in, first outempty

Task B is queued too; main still doesn't wait.

mainevent queueEDTrunningABfirst in, first outempty

main carries on. (In this run the EDT hasn't picked up a task yet; the two threads are independent.)

mainevent queueEDTwaitinguntil task C endsABCfirst in, first outempty

invokeAndWait queues task C and blocks main.

mainevent queueEDTwaitinguntil task C endsBCfirst in, first outtask Arunning

The EDT runs task A from the head of the queue (the thread is named AWT-EventQueue-0).

mainevent queueEDTwaitinguntil task C endsCfirst in, first outtask Brunning

Order is preserved: task B runs after task A.

mainevent queueEDTwaitinguntil task C endsfirst in, first outtask Crunningthen main wakes up

Task C also runs on the EDT (true). When it finishes, the waiting main wakes up.

mainevent queueEDTdonefirst in, first outempty

main is not the EDT (false). That's why components are touched only from the EDT.

Drawing Program

A Simple Drawing Program

Simple Drawing Program
curves.size() = 0, total points = 0

A 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 a repaint is 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());
            }
        });
    }
}
curve 0:(40,120)(60,60)(80,120)curve 1:(50,95)(70,95)
  • 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 is size() - 1; get(size()) throws IndexOutOfBoundsException.

Drawing Program · Step-by-step trace

Tracing the Mouse Events

curve 0:(40,120)

mousePressed: pressed at (40, 120): a new inner list is created, gets its first point and goes into the outer list.

curve 0:(40,120)(60,60)

mouseDragged: dragged to (60, 60): a point is added to the last curve; repaint requests a redraw and the line appears.

curve 0:(40,120)(60,60)(80,120)

mouseDragged: dragged to (80, 120): the same curve grows. In reality dozens of mouseDragged events arrive per second.

curve 0:(40,120)(60,60)(80,120)

mouseReleased: released. We didn't write mouseReleased, so MouseAdapter's empty body runs and nothing happens.

curve 0:(40,120)(60,60)(80,120)curve 1:(50,95)

mousePressed: pressed again at (50, 95): a second curve starts. The old curve stays as it is.

curve 0:(40,120)(60,60)(80,120)curve 1:(50,95)(70,95)

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: g can'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 paintComponent ourselves; we change the data and request repaint().

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 is actionPerformed). 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);
    }
}
Counter
Not clicked yet
The button hasn't been clicked yet.

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);
    }
}
CounterPanel objectcount0labelJLabelcomponents: 0on screen:Not clicked yet

As the object is created, its fields are initialized first: count is 0, the label is ready.

CounterPanel objectcount0labelJLabelcomponents: 0JButton "Click"listeners: 0on screen:Not clicked yet

The constructor creates a button; button is a local variable.

CounterPanel objectcount0labelJLabelcomponents: 0JButton "Click"listeners: 1lambda e -> {…}uses the count and label fieldson screen:Not clicked yet

The lambda is not run, only registered with the button. Its body will run on a click.

CounterPanel objectcount0labelJLabelcomponents: 2JButton "Click"listeners: 1lambda e -> {…}uses the count and label fieldson screen:Not clicked yet

The button and label are added to the panel (FlowLayout: side by side). The constructor ends.

CounterPanel objectcount1labelJLabelcomponents: 2JButton "Click"listeners: 1lambda e -> {…}uses the count and label fieldson screen:Not clicked yet

The user clicks: the EDT calls actionPerformed, the lambda body. count is a field, so it can be incremented.

CounterPanel objectcount1labelJLabelcomponents: 2JButton "Click"listeners: 1lambda e -> {…}uses the count and label fieldson screen:1 click(s)

setText changes the label's text; Swing repaints the label.

CounterPanel objectcount2labelJLabelcomponents: 2JButton "Click"listeners: 1lambda e -> {…}uses the count and label fieldson screen:1 click(s)

Second click: the same lambda is called again; the field becomes 2.

CounterPanel objectcount2labelJLabelcomponents: 2JButton "Click"listeners: 1lambda e -> {…}uses the count and label fieldson screen:2 click(s)

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));
  • ActionListener has just one abstract method (a functional interface), so the compiler accepts the lambda e -> … as the body of actionPerformed.
  • MouseListener has 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 label

Displays 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 field

Lets 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() + "!"));
Greeting
Your name: 
Type a name and press Enter to see the greeting.

Text Components

JTextArea and JScrollPane

JTextArea: multi-line text

Content 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 pane

When 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
JScrollPane
First line Second line Third line Fourth line Fifth line Sixth line

Case Converter

Text Converter: The Window

CaseConverter
Edit the text and convert it with the buttons.
  • In the CENTER, an 8-row × 50-column JTextArea inside a JScrollPane.
  • At the bottom (SOUTH), a JPanel holding 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.
  • area is a local variable, but the lambda only reads it (never reassigns it), so it may use it (effectively final).
  • toUpperCase() returns a new String; since String is immutable, the result must be written back with setText.
  • Write BorderLayout.CENTER in full; a bare CENTER won't compile.

Case Converter

What Happens on a Click?

User clicksTo UppercaseEvent queueActionEvent waitsEDTJButton gets the eventLambda: getText()"Java Programming"toUpperCase()new StringsetText + repaintscreen updatesarea: Java Programming

The user clicks “To Uppercase”; the operating system passes this to Java.

User clicksTo UppercaseEvent queueActionEvent waitsEDTJButton gets the eventLambda: getText()"Java Programming"toUpperCase()new StringsetText + repaintscreen updatesarea: Java Programming

Java creates an event object and puts it on the event queue.

User clicksTo UppercaseEvent queueActionEvent waitsEDTJButton gets the eventLambda: getText()"Java Programming"toUpperCase()new StringsetText + repaintscreen updatesarea: Java Programming

The EDT takes the next event; the button calls actionPerformed on every registered ActionListener, so our lambda runs.

User clicksTo UppercaseEvent queueActionEvent waitsEDTJButton gets the eventLambda: getText()"Java Programming"toUpperCase()new StringsetText + repaintscreen updatesarea: Java Programming

area.getText() reads the current text.

User clicksTo UppercaseEvent queueActionEvent waitsEDTJButton gets the eventLambda: getText()"Java Programming"toUpperCase()new StringsetText + repaintscreen updatesarea: Java Programming

toUpperCase() makes a new string; the old one is unchanged.

User clicksTo UppercaseEvent queueActionEvent waitsEDTJButton gets the eventLambda: getText()"Java Programming"toUpperCase()new StringsetText + repaintscreen updatesarea: JAVA PROGRAMMING

setText updates the area's model; the area repaints itself with repaint. The EDT moves on to the next event.

Change Calculator

Making Change

Change Calculator
Amount:
Events: 0

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 DocumentListener attached 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): the JTextField is the view; the Document from getDocument() 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

50cents–25cents–10cents–5cents–1cents–amount left: 93

The field's text "93" is read and parsed as an integer.

50cents–25cents–10cents–5cents–1cents–amount left: 93

The coin values, largest first, in an array.

50cents–25cents–10cents–5cents–1cents–amount left: 93

setText starts the report from scratch: old content is erased.

50cents× 125cents–10cents–5cents–1cents–amount left: 93

x = 50: 93 / 50 = 1 (integer division); the line is appended.

50cents× 125cents–10cents–5cents–1cents–amount left: 43

Left: 93 % 50 = 43.

50cents× 125cents× 110cents–5cents–1cents–amount left: 43

x = 25: 43 / 25 = 1 (integer division); the line is appended.

50cents× 125cents× 110cents–5cents–1cents–amount left: 18

Left: 43 % 25 = 18.

50cents× 125cents× 110cents× 15cents–1cents–amount left: 18

x = 10: 18 / 10 = 1 (integer division); the line is appended.

50cents× 125cents× 110cents× 15cents–1cents–amount left: 8

Left: 18 % 10 = 8.

50cents× 125cents× 110cents× 15cents× 11cents–amount left: 8

x = 5: 8 / 5 = 1 (integer division); the line is appended.

50cents× 125cents× 110cents× 15cents× 11cents–amount left: 3

Left: 8 % 5 = 3.

50cents× 125cents× 110cents× 15cents× 11cents× 3amount left: 3

x = 1: 3 / 1 = 3 (integer division); the line is appended.

50cents× 125cents× 110cents× 15cents× 11cents× 3amount left: 0

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 / codeEvent → report
types 9insertUpdate → 9 cents: 1 × 5, 4 × 1
types 3insertUpdate → the 93-cent report
deletes it allremoveUpdate → parseInt(""): “Not an integer…”
abc or 99999999999NumberFormatException → same message
setText("287")two events: first removeUpdate, then insertUpdate → 5, 1, 1, 0, 2
-7A 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

Layout managers

Don't hard-code coordinates; with a layout manager the layout survives different screen sizes and resolutions.

Meaningful names

upperButton, amountField instead of b1, t2: code with dozens of components stays readable.

Think event-driven

Design around “what should happen when the user does this?”; one listener per action.

Separate the GUI from the logic

Keep rules such as making change in a separate method or class; it can be tested without a GUI and reused in another one.

Build the GUI on the EDT

The body of main: SwingUtilities.invokeLater(() -> { … }).

Don't block the EDT

A long job in a listener (a download, a big computation) freezes the window; move such work to a separate thread.

Summary

Summary

ConceptEssence
Packagesjava.awt: Graphics, Color, Font, Point, layouts, events · javax.swing: the J… components
JFrameThe window: setSize/pack, setDefaultCloseOperation(EXIT_ON_CLOSE), setVisible(true) last
JPanelContainer and canvas; FlowLayout by default
DrawingOverride 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
LayoutBorderLayout (5 regions, content-pane default), FlowLayout, GridLayout, BoxLayout
EventsListener interface + add…Listener; adapters for multi-method interfaces; lambdas for single-method ones
MouseMouseListener, MouseMotionListener; MouseEvent: getX, getY, getButton
EDTSwing is single-threaded; invokeLater is asynchronous, invokeAndWait synchronous
TextJLabel displays, JTextField one line, JTextArea many lines, JScrollPane scrolls

Summary

Common Mistakes

Forgetting the import

Without import javax.swing.*; for JFrame: cannot find symbol … class JFrame.

No setVisible(true) or EXIT_ON_CLOSE

The window never appears, or the program keeps running in the background after it closes.

Misspelling the method name

paintcomponent is a new method that is never called. With @Override: method does not override or implement a method from a supertype.

Forgetting super.paintComponent(g)

The background isn't cleared; leftovers of old drawings stay on screen.

Not writing every interface method

ClickListener is not abstract and does not override abstract method mouseExited(MouseEvent) in MouseListener. Fix: MouseAdapter.

get(size()) for the last element

IndexOutOfBoundsException: Index 1 out of bounds for length 1. The last element is size() - 1.

Changing a local variable in a lambda

e -> count++: local variables referenced from a lambda expression must be final or effectively final. Fix: make the counter a field.

Writing a constant without its class

add(comp, CENTER): cannot find symbol … variable CENTER. Use BorderLayout.CENTER.

Summary

Practice Problems

  1. If the no-entry-sign panel were 200 × 100 pixels, what would r, r2, bw, bh be?
  2. What report does the change program show for 68?
  3. Where is the center of the ellipse drawn by g.drawOval(50, 50, 100, 60)?
  4. In a panel with BorderLayout, button A and then button B are added to the same NORTH region. Which one shows in the north?
  5. If the user clicks the panel once and releases, which MouseListener methods are called, in what order?
  6. What color does Color.RED.brighter() give?
Show answers
  1. r = min(100, 50) − 5 = 45, r2 = (int) 40.5 = 40, bw = 56, bh = 14.
  2. “68 cents in coins:” followed by 1 x 50c, 0 x 25c, 1 x 10c, 1 x 5c, 3 x 1c.
  3. (50 + 100/2, 50 + 60/2) = (100, 80).
  4. B: each region holds one component and the last one added wins (A stays in the panel but takes no part in the layout).
  5. mousePressed → mouseReleased → mouseClicked (plus mouseEntered as the pointer enters the panel).
  6. Still (255, 0, 0): red is already at its brightest, and the green and blue components stay 0.

Summary

Exercises

  1. Target: draw 5 nested red and white rings that scale with the panel size.
  2. Counter window: “−1”, “+1” and “Reset” buttons and a JLabel showing the value.
  3. Add a “Clear” button to the drawing program.
  4. In the drawing program, make a right click delete the last curve.
  5. Make the change program print “Amount must be positive” for negative amounts.
  6. Temperature converter: enter °C in a JTextField; a button shows °F.
Answers / hints
  1. 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.
  2. A field private static int count;; plus.addActionListener(e -> label.setText("" + (++count)));, panel with FlowLayout.
  3. Button listener: curves.clear(); repaint(); (panel and button in CENTER and SOUTH of a BorderLayout).
  4. At the start of mousePressed: if (e.getButton() == MouseEvent.BUTTON3) { if (!curves.isEmpty()) curves.remove(curves.size() - 1); repaint(); return; }; at the start of mouseDragged: if (!SwingUtilities.isLeftMouseButton(e)) return;
  5. After parseInt: if (amount < 0) { report.setText("Amount must be positive"); return; }
  6. double c = Double.parseDouble(field.getText()); result.setText(c * 9 / 5 + 32 + " °F"); 100 → 212.0 °F; catch NumberFormatException for 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).

The End

Chapter 9: Graphics and User Interfaces
Previous: Chapter 8: Input and Output · Next: Chapter 10: Threads
1 / 1 Sercan KÜLCÜ, All rights reserved.