Object-Oriented Programming with Java · Lecture Notes

Chapter 9: Graphics and User Interfaces

Until now our programs have run in the console: the program asked a question, the user typed an answer, and the results were printed one under another. The programs people use every day work with windows, buttons, text fields, and drawings. This chapter shows how to build a graphical user interface in Java. It begins with how an event-driven program differs from a console program, then covers the AWT and Swing libraries and screen coordinates. Next come windows built with JFrame and JPanel, drawing with paintComponent and Graphics, and the Point, Color, and Font classes. Layout managers arrange components in the window, and we trace pixel by pixel how a layout is computed. Mouse events, listener interfaces, adapter classes, and the event dispatch thread are the heart of the chapter. It ends with three small applications: a mouse drawing program, a text converter, and a change calculator.

Learning outcomes

Build a window
Create a window and a panel with JFrame and JPanel, add components, show the window, and close it.
Draw
Override paintComponent and draw shapes and text with Graphics; use screen coordinates and bounding rectangles.
Lay out components
Arrange components with BorderLayout, FlowLayout, GridLayout, and BoxLayout; compute the position and size of each component.
Respond to events
Handle mouse, button, and text events with listener interfaces, adapter classes, anonymous classes, and lambda expressions.
Start safely
Explain why the interface is built on the event dispatch thread with SwingUtilities.invokeLater; trace the difference between invokeLater and invokeAndWait.
Write applications
Read and modify the drawing program, the text converter, and the change calculator.

9.1Graphics programming

9.1.1Components, events, and painting

Most people use a computer through windows. A window has a title, buttons, menus, and text fields. The user clicks with the mouse, types on the keyboard, and resizes the window, and the program responds to these actions. An interface of this kind is called a graphical user interface.

Definition 9.1

A graphical user interface (GUI) is an interface in which the user interacts with a program through visual elements such as windows, buttons, menus, text fields, and drawings.

Java provides an extensive class library for building GUIs. To write a GUI program with it, you need to understand three concepts.

  • Component: The building blocks of the interface, such as windows, buttons, labels, and text fields. Every component is an object of some class. A button is an object created from the JButton class; its text, color, and size are stored in the fields of that object.
  • Event handling: User actions such as a mouse click or a key press are captured, and methods that respond to them are called.
  • Painting: Shapes are drawn, the screen is updated, and components are displayed.
build the componentswait for an eventevent occurslistener runswhen done, go back to waitingclick, key, mouseactionPerformed…
Figure 9.1: The life of a GUI program. The components are built, the program waits for an event, and when an event arrives the matching listener method runs; then the program waits again.

A GUI program is like a shop waiting for customers. First the window display is prepared: the components are created and placed in the window. Then the program waits. Whatever the customer touches, the assistant responsible for that item springs into action. In the program, the display corresponds to the components, the touch to an event, and the assistant to a listener method (Figure 9.1).

9.1.2Console programs and GUI programs

In a console program the flow is sequential. The main method runs from beginning to end. When the program needs input, it asks the question itself and reads a line from the keyboard with Scanner. The result is printed with System.out.println. When main ends, the program ends.

A GUI program flows differently. main only builds the interface and returns. After that the program waits for the user's move. When the user presses a button or clicks a panel, the matching method runs. This style of execution is called event-driven programming.

Definition 9.2

An event is a user action, such as a click, a key press, or a mouse drag, or a notification from the system. In an event-driven program, the order in which events arrive, not the order of lines in the code, determines the flow.

Table 9.1: Comparison of console programs and GUI programs.
Console programGUI program
FlowSequential: main runs from start to end, and the program asks the questionsEvent-driven: the program waits for the user's move
InputA line is read from the keyboard with ScannerButtons, text fields, and the mouse; listener methods are called
OutputSystem.out.printlnThe text of components changes, or the panel is repainted
TerminationThe program ends when main endsKeeps running until the window is closed, even after main ends
Libraryjava.util, java.iojava.awt, javax.swing, java.awt.event

The last two rows of the table matter. In a GUI program, the program keeps running even though main has finished. The reason is that Java starts a separate thread when a window opens. This thread waits on the event queue and passes each incoming event to the matching listener. The JVM does not exit while this thread is running.

In a GUI program, the answer to “what happens next?” is not the order of the code; it is the user's next action. That is why most of the code consists of listeners of the form “when this happens, do that.” The programmer writes a response for each action but does not know in what order the actions will arrive.

Common mistake

Trying to wait for user input in a while loop in a GUI program. A “loop until the user presses the button” written out of console habit keeps the event thread busy, and the window freezes. In a GUI program Java does the waiting; the programmer only registers the listener.

9.1.3AWT and Swing

Java's graphics classes are spread over two libraries. Both come with the JDK; nothing extra needs to be installed.

  • AWT (Abstract Window Toolkit), package java.awt: Java's first graphics library. Today it is used mostly for its shared classes: Graphics, Color, Font, Point, the layout managers, and the event classes (java.awt.event).
  • Swing, package javax.swing: a library built on top of AWT in which Java itself draws the components. Class names start with J: JFrame, JPanel, JButton, JLabel.

The difference between the two libraries lies in how components are drawn. When AWT needs a button, it uses the operating system's own button, so the same program looks different on Windows and on Linux. Swing paints the button itself, so the look is the same on every system and is under Java's control. In this chapter the components come from Swing, while the drawing and helper classes come from AWT. A typical GUI program therefore imports both packages: import java.awt.*; and import javax.swing.*;.

ComponentContainerWindowJComponentFrameJFrameJPanelJButtonJLabelJScrollPaneJTextComponentJTextFieldJTextAreajava.awtjavax.swing
Figure 9.2: The inheritance tree of the GUI classes. A hollow triangle means “is derived from.” JFrame is an AWT window; the other Swing components derive from JComponent.

Figure 9.2 shows how inheritance is used in the GUI library. At the root of the tree is Component: anything with a position and size on the screen is a component. A Container is a component that can hold other components. Two branches leave Container. The first holds Window, Frame, and finally JFrame. The second holds JComponent, the common superclass of the Swing components. JPanel, JLabel, and the text components derive from JComponent directly or by a short path. JButton has the AbstractButton class in between.

This tree has a practical consequence. If a method expects a Component as a parameter, you can pass it a button, a label, or a panel. Polymorphism is an everyday tool here. For example, the panel.add(...) method accepts any component.

9.1.4Screen coordinates

A graphical application is built in three steps. First, components are added to the interface using Java's graphics classes. Second, event-handling methods are defined that respond to the user's actions. Finally, the visuals are produced with methods such as paint() or paintComponent(). Before we start drawing, we need to know how the screen is addressed.

The screen is a grid of pixels. Every pixel has a column number (x) and a row number (y). Coordinates are integers measured from the top-left corner of the component.

x = 0x = getWidth()y = 0y = getHeight()(0, 0) top-left cornerx grows to the right, y grows DOWNWARD
Figure 9.3: The screen coordinate system. The origin is at the top-left corner; x grows to the right and y downward. The line, rectangle, and ellipse are made of pixels.
Definition 9.3

Screen coordinates identify a pixel inside a component by an integer pair (x, y). (0, 0) is the top-left pixel of the component. x grows to the right and y downward. The bottom-right pixel is (getWidth() − 1, getHeight() − 1).

The most important difference from the axes of mathematics is the direction of y. In mathematics y grows upward; on the screen it grows downward. This choice comes from the history of displays: cathode-ray tubes drew the picture from top to bottom, line by line. As a result, a point whose y value increases moves down the screen. Decreasing y moves the point up.

Example 9.1

A panel is 300 pixels wide and 160 pixels high. What are the coordinates of the top-right, bottom-left, and center pixels?

Columns are numbered 0 to 299 and rows 0 to 159. The top-right pixel is (299, 0) and the bottom-left pixel is (0, 159). For the center pixel, the width and height are divided by two: (300 / 2, 160 / 2) = (150, 80). If the numbers were odd, integer division would discard the fraction; for example, 261 / 2 = 130.

9.1.5Canvas, pen, color, and font

Drawing needs three things: a surface to draw on, a pen that does the drawing, and the pen's properties.

  • Canvas: a surface on which a picture can be drawn. In Swing, a JPanel is usually used. In AWT there is a Canvas class for this job. The programmer derives a subclass from JPanel and draws inside it.
  • The Graphics class: the “pen” that does the drawing. Its methods have names such as drawLine(), drawRect(), fillOval(), drawString(), and drawImage().
  • Color and Font: Color sets the pen's color and Font sets 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
Figure 9.4: A JPanel canvas inside a JFrame window. The Graphics object does the drawing.

The pen analogy also explains a rule. The Graphics object is the pen in the programmer's hand. setColor changes the pen. Until the pen is changed again, all drawing uses the same color. The same holds for the font: after a call to setFont, every drawString uses the new font. A Graphics object is therefore a stateful object: it remembers its own color and font.

9.1.6Drawing with paintComponent

The way to draw permanently on a panel is to override the paintComponent method in a class derived from JPanel.

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

The class extends JPanel and overrides the superclass's paintComponent(Graphics g) method. The @Override annotation tells the compiler that “this method replaces a method of the superclass.” If the method name is misspelled, the compiler sees the annotation and reports an error. The first line of the body is super.paintComponent(g): it performs the superclass's own painting, which fills the background with the background color. Then the pen is switched to blue. drawRect(20, 30, 50, 70) draws the outline of a rectangle whose top-left corner is at (20, 30), 50 pixels wide and 70 pixels high. The last line writes a text at the point (100, 100).

Hello, Java Graphics!
Figure 9.5: The output of DrawPanel for a 300 × 160 panel: a blue outline and text in the same color.

Notice something in this code: nothing in the program ever calls paintComponent. Swing calls it. Swing runs the method when the window first opens, when its size changes, when another window that covered it is dragged away, or when the program requests a repaint with repaint(). When it calls the method, it passes a ready-made Graphics g object, which is tied to the region currently being painted.

To see which drawing calls the method actually makes, we can use Swing's DebugGraphics class. It is a pen that writes each drawing call as a line of text. Running DrawPanel with this pen on a 300 × 160 image shows the following calls (abbreviated):

setColor(238, 238, 238)
fillRect(0, 0, 300, 160)
setColor(0, 0, 255)
drawRect(20, 30, 50, 70)
drawString("Hello, Java Graphics!", 100, 100)

The programmer did not write the first two lines. They are the work of super.paintComponent(g): the pen is switched to the panel's background color, the light gray (238, 238, 238), and the whole panel is filled with it. The next three lines are the calls the programmer wrote.

Definition 9.4

paintComponent(Graphics g) is the method with which a Swing component draws its own contents. Swing calls this method whenever the component needs to be repainted. A class that wants to do its own drawing overrides the method and writes super.paintComponent(g) first in the body.

A graphics object can also be obtained with panel.getGraphics(). However, drawing done with this object is not permanent. The next time the window is repainted, for example after it is minimized and restored, Swing calls paintComponent and whatever was drawn through getGraphics() is erased. The way to draw permanently is paintComponent. The data of the drawing is kept in fields, and the method regenerates the picture from this data on every call.

The position of text also has a subtlety. The y parameter of drawString is not the top edge of the text but its baseline. The baseline is the line on which the letters “sit.” In the call drawString("Hello, Java Graphics!", 100, 100), the bodies of the letters stay above row 100; only the tails of letters such as “g” and “j” drop below that line.

Common mistake

Writing drawString(text, x, 0) and expecting the text to appear at the very top of the panel. Because y = 0 is the baseline, almost all of the letters end up outside the panel, in the invisible region. For the text to be visible, y must be at least the height of the font; for a 24-point font, a value around 30–40 is safe.

9.1.7Graphics drawing methods

The commonly used methods of the Graphics class are collected in Table 9.2. The names follow a pattern: methods starting with draw… draw only the outline, and those starting with fill… draw the shape filled.

Table 9.2: The basic drawing methods of the Graphics class.
MethodWhat it does
drawLine(x1, y1, x2, y2)A line between two points
drawRect(x, y, w, h)A rectangle outline; (x, y) is the top-left corner
fillRect(x, y, w, h)A filled rectangle
drawOval(x, y, w, h)The ellipse that fits in this rectangle (a circle if w = h)
fillOval(x, y, w, h)A filled ellipse or disk
drawString(s, x, y)Text; y is the baseline
setColor(c) / setFont(f)The color or font of later drawing
drawImage(image, x, y, null)Draws an image at the point (x, y)

Ellipses and circles are specified not by their centers but by their bounding rectangles: you give the top-left corner and the size of the rectangle in which the ellipse fits.

Definition 9.5

The bounding rectangle of a shape is the smallest axis-parallel rectangle that completely encloses it. drawOval(x, y, w, h) draws the ellipse inside the rectangle whose top-left corner is (x, y) and whose size is w × h.

(40, 40)width 16090
Figure 9.6: drawOval(40, 40, 160, 90). The ellipse fits in the 160 × 90 rectangle whose top-left corner is (40, 40).

To draw a circle with center (cx, cy) and radius r, compute the top-left corner of the bounding square. The square extends r to the left of and above the center, and its side is 2r. The result is fillOval(cx − r, cy − r, 2r, 2r). Conversely, for a given call drawOval(x, y, w, h), the center of the ellipse is (x + w / 2, y + h / 2).

Example 9.2

Where is the center of the ellipse drawn by g.drawOval(50, 50, 100, 60)? Which range of pixels does it cover?

The center is (50 + 100 / 2, 50 + 60 / 2) = (100, 80). The ellipse starts at 50 horizontally and at 50 vertically. If it is drawn on an image and the painted pixels are counted, x runs from 50 to 150 and y from 50 to 110. Methods that draw outlines also paint the right and bottom edge of the boundary: a draw… shape is w + 1 pixels wide and h + 1 pixels high, whereas fill… paints exactly w × h pixels.

The difference in the last sentence is small but real. In the call drawRect(20, 30, 50, 40), the bottom-right corner pixel of the outline is (70, 70), and (71, 70) stays empty. With the same arguments, fillRect paints up to (69, 69). When an outline is drawn over a filled rectangle, this one-pixel difference becomes visible.

9.1.8Code trace: the drawing order of shapes

The following panel uses each of the basic methods once.

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);
    }
}
Hello
Figure 9.7: The output of ShapesPanel: a line, a rectangle outline, a filled rectangle, an ellipse, a filled disk, and text.

There is no setColor call anywhere in the code. When no color is given, the pen draws with the panel's foreground color. In Swing's default look this is the dark gray (51, 51, 51); in a running program getForeground() returns this value. Table 9.3 traces the steps of the method.

Table 9.3: Trace of ShapesPanel.paintComponent.
StepLineVariablesExplanation
14: super.paintComponent(g);g=Graphics (dark gray pen)Swing calls this method itself. super.paintComponent(g) clears the canvas with the background color.
25: g.drawLine(10, 10, 110, 60);x1=10, y1=10, x2=110, y2=60A line between two points. Because y grows downward, the line goes to the right and down.
36: g.drawRect(130, 10, 80, 50);x=130, y=10, w=80, h=50drawRect: (x, y) is the top-left corner; only the outline is drawn, and the inside stays empty.
47: g.fillRect(230, 10, 80, 50);x=230, y=10, w=80, h=50fillRect: a rectangle of the same size, filled with the pen's color.
58: g.drawOval(10, 80, 100, 60);x=10, y=80, w=100, h=60drawOval: an ellipse that fits in the dashed box. (10, 80) is the corner of the box, not of the ellipse.
69: g.fillOval(130, 80, 60, 60);x=130, y=80, w=60, h=60Since w = h, a filled disk: center (160, 110), radius 30.
710: g.drawString("Hello", 230, 115);s="Hello", x=230, y=115In drawString, y is the baseline of the text: the letters are written above 115.
811: }—The method ends; every time the window is repainted (a size change, repaint()), everything is drawn again from the start in the same order.

The line in step 2 goes from (10, 10) to (110, 60). Because the second point has a larger y, the line goes right and down. Steps 3 and 4 draw two rectangles of the same size. One is only an outline; the other is filled with the pen's color. In step 5, the point (10, 80) is the corner of the bounding box, not of the ellipse.

(0, 0)x →(10, 80)
Figure 9.8: Step 5. drawOval(10, 80, 100, 60): the ellipse fits in the bounding box shown with a dashed line.

In step 6, the width and height are equal, so a filled disk is drawn. The center is (130 + 30, 80 + 30) = (160, 110) and the radius is 30. In step 7, the baseline of the text is y = 115; the letters are written above this line. When the method ends, the panel is complete. Every time the window is repainted, the same calls are made again from the start in the same order.

Drawings are painted on top of one another. A shape drawn later covers an earlier one. In this program the shapes do not overlap, so the order is not visible. When shapes overlap, the one drawn last stays on top.

Common mistake

Forgetting the line super.paintComponent(g). This line clears the background. Without it the panel is not painted with its background, and leftover images from the previous drawing or from other windows may remain on the screen. In animations in particular, a moving shape leaves a trail wherever it has been.

9.2Windows and panels

9.2.1The JFrame class

All the components of a GUI program live inside a window. In Swing, a window is created with the JFrame class.

Definition 9.6

JFrame is a top-level window with a title bar and minimize and close buttons on the screen. It is not placed inside another component; other components are added to its content pane.

Table 9.4: Frequently used calls with JFrame.
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 (to the content pane)
frame.setSize(400, 300);Width and height (pixels, including the borders)
frame.pack();Sets the size to the size preferred by the components inside
frame.setLocation(x, y);The position of the window on the screen; setLocationRelativeTo(null) centers it
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);Ends the program when the window is closed
frame.setVisible(true);Makes the window visible (usually called last)

There are two ways to size a window. setSize gives the size directly; this size includes the title bar and the borders. pack() adds up the sizes preferred by the components inside and makes the window exactly that large. In a window whose components are arranged by a layout manager, pack() usually gives a better result, because the content fits in the window even when the font or the screen resolution changes.

The add call actually adds the component not to the window itself but to its content pane. The content pane is the inner area below the title bar. In old Java versions you had to write frame.getContentPane().add(...). Since Java 5, frame.add(...) makes this call itself. The examples in this chapter use both forms; they mean the same thing.

9.2.2The 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 program imports the JFrame and SwingUtilities classes. main does not build the window itself; it leaves the building to the event dispatch thread (EDT) with SwingUtilities.invokeLater. Swing components should be used only from this thread; the reason is explained in 9.6.5. The code running on the EDT creates a window titled “Java JFrame Example,” sets its size to 400 × 300, sets the close behavior, and makes the window visible. The window is empty. main ends as soon as it has queued the work, but the program keeps running until the window is closed.

This short program has three pitfalls:

  • If setVisible(true) is forgotten, the window is created in memory but never appears on the screen. The program raises no error; it simply looks as if nothing is happening.
  • If EXIT_ON_CLOSE is not given, the default behavior is HIDE_ON_CLOSE. When the user presses the × button, the window is hidden, but the program keeps running in the background. In a development environment this shows up as a pile of programs that were forgotten and never stopped.
  • If no size is given, the window opens at nearly 0 × 0, just the size of its title bar.

The four constants accepted by setDefaultCloseOperation are defined in the WindowConstants interface. DO_NOTHING_ON_CLOSE (0) prevents closing altogether. HIDE_ON_CLOSE (1) hides the window. DISPOSE_ON_CLOSE (2) destroys the window; if no other windows remain, the program may end. EXIT_ON_CLOSE (3) calls System.exit(0).

If this program is run in an environment with no display, it produces an interesting result. Java recognizes a display-less environment as headless mode. In this mode, the call new JFrame(...) throws java.awt.HeadlessException, because there is no screen to show it on. Components such as panels, buttons, and text fields can still be created in this mode. Most of the outputs given in this chapter were obtained this way, by running the components directly without opening a window.

9.2.3The JPanel class

Definition 9.7

A container is a component that holds other components. JPanel is the general-purpose container in the javax.swing package; it is used to group and arrange the components inside a window and to draw on.

JPanel has four uses:

  • Grouping: Complex layouts are built by nesting several panels. For example, the row of buttons at the bottom of a window is collected in a separate panel.
  • Customizing: setBackground(), setBorder(), and setPreferredSize() change its color, its border, and its preferred size.
  • Serving as a canvas: Drawings, animations, and graphics are done on a panel: derive from JPanel and override paintComponent.
  • Splitting up code: Each panel can be a class of its own. A large interface is thus divided into small pieces that can be understood separately.
JFramewindowcontent panegetContentPane()JPanelpanelJButtonbuttonJLabellabelJPanelinner panel
Figure 9.9: Nested components. A JFrame contains the content pane, the content pane contains a JPanel, and this panel contains a button, a label, and another panel.

The structure in Figure 9.9 is a tree. The root is the window and the leaves are components such as buttons and labels. The interior nodes are containers. When a container is repainted, it first paints itself and then the components inside it. The same rule applies at every level of the component tree.

9.2.4A panel 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);
        });
    }
}

Like the previous example, the program builds the interface on the event dispatch thread with invokeLater. It creates a panel and sets its background to Color.LIGHT_GRAY, that is, the light gray (192, 192, 192). A button labeled “Click” is added to the panel. Then the window is created, the panel is added to it, and the window is shown at 300 × 150. The button has no listener; when clicked it looks pressed, but nothing happens.

In the window, the button sits at the top center of the panel, and the panel fills the whole window. Layout managers explain both observations. The default layout manager of JPanel is FlowLayout. This manager arranges components at their preferred sizes, row by row, centered. Since the panel holds a single button, the button is placed in the middle of the first row. The content pane of a JFrame uses BorderLayout. A panel added without a region goes to the center region, and the center takes all the remaining space.

Example 9.3

Let this panel be 284 × 111 pixels. If the preferred size of the “Click” button is 61 × 26, what is the position of the button?

By default, FlowLayout leaves a gap of 5 pixels between components and at the edges. The available width is 284 − 2 × 5 = 274. The button is placed in the middle of this width: x = 5 + (274 − 61) / 2 = 5 + 106 = 111. The row starts 5 pixels below the top edge: y = 5. When the panel is brought to this size in headless mode and the layout is computed, the bounds of the button come out as [x=111, y=5, width=61, height=26]. The size of the button depends on the font; on another system it may differ by a few pixels.

9.3Drawing tools

Three small classes are used constantly in drawing: Point, which holds a point; Color, which holds a color; and Font, which holds a typeface. All three are in the java.awt package.

9.3.1The Point class

Definition 9.8

java.awt.Point is the class that holds a point (x, y) on the screen. Its fields x and y are public int. getX() and getY() return the same values as double.

Point is a deliberate exception to the principle of encapsulation: its fields are public and can be read and written directly. Because point coordinates are accessed so often in graphics code, the library chose simplicity. The class also has methods. The following code uses most of them.

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));
30.0 40.0
30 40
50.0
java.awt.Point[x=60,y=80]
java.awt.Point[x=65,y=70]
5.0
Table 9.5: Trace of the Point example.
StepLineVariablesNew output
11: Point p = new Point(30, 40);p=(30, 40)—
22: double px = p.getX();p=(30, 40), px=30.0—
33: double py = p.getY();p=(30, 40), px=30.0, py=40.0—
44: System.out.println(px + " " + py);p=(30, 40), px=30.0, py=40.030.0 40.0
55: System.out.println(p.x + " " + p.y);p=(30, 40), px=30.0, py=40.030 40
66: System.out.println(p.distance(0, 0));p=(30, 40), px=30.0, py=40.050.0
77: p.setLocation(60, 80);p=(60, 80), px=30.0, py=40.0—
88: System.out.println(p);p=(60, 80), px=30.0, py=40.0java.awt.Point[x=60,y=80]
99: p.translate(5, -10); // 5 right, 10 upp=(65, 70), px=30.0, py=40.0—
1010: System.out.println(p);p=(65, 70), px=30.0, py=40.0java.awt.Point[x=65,y=70]
1111: System.out.println(Point.distance(0, 0, 3, 4));p=(65, 70), px=30.0, py=40.05.0

In step 1 the point (30, 40) is created. In steps 2 and 3, the values of getX() and getY() are stored in double variables. Step 4 prints these values: 30.0 40.0. The decimal point shows that the value is a double. Step 5 accesses the fields directly; since p.x is an int, it prints 30 40. The same number written in two different forms shows how the type affects the output.

In step 6, distance(0, 0) computes the distance of the point from the origin. By the Pythagorean theorem, √(30² + 40²) = √2500 = 50.0. In step 7, setLocation(60, 80) moves the point to a new position. px and py do not change: they are copies taken in steps 2 and 3 and are no longer connected to the object. In step 8, println(p) calls the object's toString() method and prints the class name and the fields: java.awt.Point[x=60,y=80].

(0, 0)(65, 70)
Figure 9.10: Step 9. translate(5, -10) moves the point 5 pixels to the right and 10 pixels up: from (60, 80) to (65, 70).

translate(dx, dy) in step 9 is a relative shift: dx is added to x and dy to y. Since dy = −10, y decreases from 80 to 70 and the point moves up the screen (Figure 9.10). Point.distance(0, 0, 3, 4) in the last line is a static method. It needs no object; it takes the coordinates of two points and returns 5.0.

Example 9.4

After the lines Point p = new Point(10, 20); Point q = p; q.translate(5, 5); p.setLocation(p.x * 2, p.y);, what are p, q == p, and q.distance(30, 29)?

Point q = p; does not create a new point. Both variables refer to the same object. q.translate(5, 5) moves this shared object to (15, 25). p.setLocation(15 * 2, 25) moves the object to (30, 25). Because p and q are the same object, q == p is true. Between (30, 25) and (30, 29) there is a vertical line: the distance is 4.0. If an independent copy is wanted, write new Point(p).

java.awt.Point[x=30,y=25] true
4.0
140 70 35

The third line of the output relates to the next class: new Color(200, 100, 50).darker() gives the components of a color.

9.3.2The Color class

java.awt.Color holds the color of the interface and of drawings. Every color on the screen is a mixture of three primary colors: red, green, and blue. This scheme is called RGB.

Definition 9.9

An RGB color is a triple in which the red, green, and blue components are each an integer in the range 0–255. new Color(int red, int green, int blue) creates a color object from this triple. (0, 0, 0) is black and (255, 255, 255) is white.

There are two ways to obtain a color. The first is the predefined constants, such as Color.RED, Color.GREEN, Color.WHITE, and Color.LIGHT_GRAY. These constants also have lowercase aliases (Color.red); both refer to the same object. The second is to create a new object from an RGB triple. A value outside 0–255 throws IllegalArgumentException; the message of the call new Color(300, 0, 0) is Color parameter outside of expected range: Red.

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]

Two methods produce darker and lighter shades of a color. darker() multiplies each component by 0.7 and truncates to an integer. brighter() divides each component by 0.7 and caps the result at 255. Neither method changes the original color; each returns a new Color object. Color objects are immutable.

Table 9.6: Some colors and their RGB components (verified by running them).
ExpressionRGBCalculation
Color.RED(255, 0, 0)predefined constant
Color.BLUE(0, 0, 255)predefined constant
Color.LIGHT_GRAY(192, 192, 192)predefined constant
new Color(255, 128, 0)(255, 128, 0)orange
orange.darker()(178, 89, 0)255 × 0,7 = 178,5 → 178; 128 × 0,7 = 89,6 → 89
Color.RED.darker()(178, 0, 0)0 × 0,7 = 0
Color.GREEN.darker()(0, 178, 0)the background of the no-entry sign
new Color(100, 50, 0).brighter()(142, 71, 0)100 / 0,7 = 142,8 → 142; 50 / 0,7 = 71,4 → 71
Color.RED.brighter()(255, 0, 0)255 is already at the limit; components that are 0 stay 0
Color.RED.darker().brighter()(254, 0, 0)178 / 0.7 = 254.2 → 254: truncation loss

The last row of the table carries a warning. darker() and brighter() are not exact inverses of each other. Each operation truncates the result to an integer, and the truncated fraction does not come back. If you darken red and then brighten it again, you get (254, 0, 0), not (255, 0, 0).

You may also ask why brighter() leaves zero components unchanged. Zero divided by 0.7 is still zero. So pure red does not turn pink when it is “brightened”; it stays the same. The library handles one special case separately: when black (0, 0, 0) is brightened it becomes (3, 3, 3), because otherwise black could never be brightened at all.

Example 9.5

Which components does new Color(200, 100, 50).darker() give?

Each component is multiplied by 0.7 and truncated: 200 × 0.7 = 140, 100 × 0.7 = 70, 50 × 0.7 = 35. The result is (140, 70, 35). These values are the same as the third line of the previous example's output.

9.3.3The Font class

java.awt.Font sets the typeface, style, and size of text. The constructor takes three parameters: new Font(name, style, size).

Table 9.7: The parameters of the Font constructor.
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); both at once: Font.BOLD | Font.ITALIC
sizeAn integer size in points, for example 24

A logical name is a name that Java maps to a real font on every system. "Serif" often corresponds to Times New Roman on Windows, and "Monospaced" to Courier New. If a real font name is given and that font is not installed, Java falls back to "Dialog". Portable programs therefore prefer logical names.

The style constants are bit flags. BOLD uses bit 1 of the number and ITALIC uses bit 2. The | operator (bitwise OR) combines two flags: 1 | 2 = 3. For the object new Font("Serif", Font.BOLD | Font.ITALIC, 20), getStyle() returns 3; isBold() and isItalic() are both true.

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

The method first switches the pen to the blue (0, 102, 204). The first text is written at (20, 40) in bold 24-point Serif. Then the font is changed, and the second text is written at (20, 70) in 14-point Monospaced. Since the color is not changed, both texts are in the same blue.

JavaSwing
Figure 9.11: The output of FontPanel: “Java” in bold Serif 24 point and “Swing” in Monospaced 14 point.

The same Font object is also used in components such as JLabel: label.setFont(f). To derive a new font from an existing one, there is the deriveFont method. f.deriveFont(Font.ITALIC, 18f) returns a new object in the same family, italic and 18 points. f does not change.

Common mistake

Writing f.deriveFont(18) to change only the size. The version of deriveFont with a single int parameter changes the style, not the size. For a bold 24-point font, this call interprets 18 as a style and leaves the size at 24. When tried, the result is style 0, size 24. For the size, use the float version: f.deriveFont(18f).

9.4Layout managers

9.4.1What is a layout manager?

Suppose five buttons are to be put in a window. The position and size of each button could be given by hand: “the first button is at (10, 10), 80 × 30.” This approach runs into a problem. When the user enlarges the window, the buttons stay in the top-left corner. When the screen resolution or the font changes, the button texts no longer fit in the boxes. Java hands this job to an object.

Definition 9.10

A layout manager is an object that computes the position and size of the components inside a container according to rules. It is given to the container with setLayout: panel.setLayout(new GridLayout(2, 3));.

A layout manager is used instead of giving coordinates by hand. When the window grows, or the font or the screen resolution changes, the layout is recomputed automatically. The programmer only chooses the rule: “arrange row by row,” “place in five regions,” “divide into equal cells.” This chapter covers four of Java's standard managers.

1234 NSWECENTER 123456 123
Figure 9.12: Four layout managers. From left to right: FlowLayout (left to right, wrapping to the next row when full; the JPanel default), BorderLayout (five regions; the default of the JFrame content pane), GridLayout(2, 3) (cells of equal size), BoxLayout.Y_AXIS (a single column).

The more flexible but more complicated GridBagLayout builds a grid of cells of different sizes. You rarely need it. It is enough to nest panels and give each one a simple manager. For example, the content pane of a window uses BorderLayout, while the button strip at the bottom is a separate panel that uses FlowLayout.

The behavior of layout managers can be followed interactively in the Swing Layout Managers simulator. As the window size changes, you can see how each of the four managers recomputes its layout.

9.4.2Code trace: how FlowLayout fills rows

The best way to understand how a layout manager works is to compute a layout by hand. The following code adds five buttons of different widths to a panel 260 pixels wide and prints the computed positions.

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());
52, 5
147, 5
37, 40
152, 40
90, 75

The default settings of FlowLayout are FlowLayout(CENTER, 5, 5): rows are centered, and a gap of 5 pixels is left between components horizontally and vertically. The same gap is left at the edges of the panel. The preferred size of each button is given with setPreferredSize: the widths are 90, 60, 110, 70, and 80; the heights are 30.

Table 9.8: Layout trace of FlowLayout.
StepLineVariablesNew outputExplanation
11: int[] w = {90, 60, 110, 70, 80};
2: JPanel panel = new JPanel(); // FlowLayout(CENTER, 5, 5)
3: panel.setSize(260, 120);
w=[90, 60, 110, 70, 80], panel=260×120—The default manager of JPanel is FlowLayout: centered, with a 5-pixel gap between components. The dashed lines show the margin.
25: JButton b = new JButton("B" + i);
6: b.setPreferredSize(new Dimension(w[i], 30));
7: panel.add(b);
i=0, b=B0 (90×30)—add only appends the button to a list; its position is still (0, 0) and its size 0 × 0.
34: for (int i = 0; i < w.length; i++) {
5: JButton b = new JButton("B" + i);
6: b.setPreferredSize(new Dimension(w[i], 30));
7: panel.add(b);
i=4, b=B4 (80×30)—The loop is over: five buttons were added, and none has been placed. Placement happens only when the layout is computed.
49: panel.doLayout(); // compute positionsrow=1, width=90+5+60=155—doLayout(): the available width is 260 − 2 × 5 = 250. B0 and B1 fit: 155 pixels.
59: panel.doLayout(); // compute positionsrow=1, trial=155+5+110 = 270 > 250—If B2 is added too, the row would be 270 pixels: it does not fit and goes to the next row.
69: panel.doLayout(); // compute positionsrow=1, x0=5+(250−155)/2 = 52—Row 1 is centered: B0 x = 52, B1 x = 52 + 90 + 5 = 147, y = 5.
79: panel.doLayout(); // compute positionsrow=2, width=110+5+70 = 185—Row 2: B2 and B3 (185 pixels); with B4 it would be 270. Centering: x0 = 5 + (250 − 185)/2 = 37.
89: panel.doLayout(); // compute positionsrow=3, x0=5+(250−80)/2 = 90—B4 is alone in the third row; y = 5 + 30 + 5 + 30 + 5 = 75.
910: for (Component c : panel.getComponents())
11: System.out.println(c.getX() + ", " + c.getY());
c=B0 … B452, 5 ⏎ 147, 5 ⏎ 37, 40 ⏎ 152, 40 ⏎ 90, 75The computed bounds are printed. If the panel gets wider, the rows are recomputed and the buttons move.

The first lesson of the trace is in steps 2 and 3. add appends the button to the container's component list but does not place it. When the loop ends, all five buttons are at (0, 0) with size 0 × 0. Placement happens only when the layout is computed. In a real window, this is triggered automatically by pack(), setVisible(true), or a change of window size. In the example, doLayout() is called explicitly.

doLayout() fills the rows as follows. The available width is the panel width minus the two edge gaps: 260 − 2 × 5 = 250. Buttons are added to a row in order. B0 (90) and B1 (60), with the 5-pixel gap between them, take 155 pixels; they fit. If B2 were added too, the row would be 155 + 5 + 110 = 270 pixels. Since 270 > 250, B2 goes to the next row.

When a row is closed, it is centered. The unused width of the row is distributed equally to both sides: x0 = 5 + (250 − 155) / 2 = 5 + 47 = 52. Integer division truncates 47.5 to 47. B0 is placed at x = 52 and B1 at x = 52 + 90 + 5 = 147; both have y = 5.

panel 260 × 120B0B1B2B3B4added:B0 90B1 60B2 110B3 70B4 80
Figure 9.13: Step 8. Three rows have been built; B4 is centered alone in the third row.

The second row, with B2 (110) and B3 (70), takes 185 pixels. If B4 were added, it would be 185 + 5 + 80 = 270; again it does not fit. Centering: x0 = 5 + (250 − 185) / 2 = 5 + 32 = 37. B2 is placed at x = 37 and B3 at x = 37 + 110 + 5 = 152. The y of the row is the bottom of the previous row plus the gap: 5 + 30 + 5 = 40. B4 is alone in the third row: x0 = 5 + (250 − 80) / 2 = 90, y = 5 + 30 + 5 + 30 + 5 = 75. The calculation matches the output exactly.

If the panel gets wider, the rows are recomputed. When the same panel is widened to 400 pixels and the layout is recomputed, the available width becomes 390. The first four buttons (90 + 60 + 110 + 70 + 3 × 5 = 345) fit in one row; B4 goes to the second row:

(27, 5) (122, 5) (187, 5) (302, 5) (160, 40)
Example 9.6

Three components of size 80 × 30 are added to a FlowLayout panel 200 pixels wide. What are the positions of the components?

The available width is 200 − 10 = 190. The first two components take 80 + 5 + 80 = 165 pixels; if the third were added, it would be 250, which does not fit. The start of the first row is 5 + (190 − 165) / 2 = 5 + 12 = 17. The components are placed at (17, 5) and (102, 5). The third component is in the second row: x = 5 + (190 − 80) / 2 = 60, y = 40. The program run in headless mode gave the same values.

9.4.3BorderLayout

BorderLayout divides the container into five regions: NORTH, SOUTH, WEST, EAST, and CENTER. It is suitable for showing components with different priorities in an orderly way: the toolbar at the top, the status line at the bottom, and the main content in the middle.

NORTHSOUTHWESTEASTCENTER(remaining space)
Figure 9.14: The regions of BorderLayout.

The manager's rules are as follows:

  • A component added without a region goes to the center: add(b) and add(b, BorderLayout.CENTER) are the same.
  • Each region holds a single component. A second addition to the same region replaces the first.
  • North and south take the whole width; their height is the component's preferred height. West and east take the height left between north and south; their width is the preferred width. The center fills everything that remains.
  • setHgap() and setVgap() set the horizontal and vertical gap between regions in pixels. The same values can also be given to the constructor: new BorderLayout(5, 5).

The second rule has a subtle side. When a second component is added to the same region, the first is not removed from the container. The container's component count is 2, but the manager attaches only the last one added to that region. The first component takes no part in the layout and keeps the size 0 × 0. It is not visible on the screen.

Common mistake

Adding two components to a window without specifying a region: f.add(new JButton("One")); f.add(new JButton("Two"));. Because the content pane uses BorderLayout, both go to the center and the last one added wins. Only “Two” is visible, and it fills the whole area. Tried on a 300 × 200 BorderLayout panel, “Two” comes out as (0, 0, 300, 200) and “One” as 0 × 0. Side-by-side arrangement is the behavior of FlowLayout; for that, put the buttons in a JPanel first.

9.4.4Code trace: filling the regions

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

The code creates a panel and a BorderLayout object, sets the gaps to 5 pixels, and gives the manager to the panel. Then a button is added to each of the five regions. Table 9.9 describes the effect of each addition on the layout.

Table 9.9: Filling the regions of BorderLayout.
StepLineExplanation
11: JPanel panel = new JPanel();
2: BorderLayout layout = new BorderLayout();
3: layout.setHgap(5);
4: layout.setVgap(5);
5: panel.setLayout(layout);
The panel will use BorderLayout; there is a 5-pixel gap between regions. There are no components yet.
26: panel.add(new JButton("North"), BorderLayout.NORTH);The North button takes the whole width; its height is the button's preferred height.
37: panel.add(new JButton("South"), BorderLayout.SOUTH);South also takes the whole width and sits at the very bottom.
48: panel.add(new JButton("West"), BorderLayout.WEST);West takes the height left between north and south; its width follows its text.
59: panel.add(new JButton("East"), BorderLayout.EAST);East sits at the right edge.
610: panel.add(new JButton("Center"), BorderLayout.CENTER);Center fills all the remaining space. If the window is enlarged, the center grows the most.
NorthSouthWestEastCenter
Figure 9.15: Step 6. All five regions are filled; the center has taken all the remaining space.

The pixel values depend on the panel size and on the buttons' preferred sizes. If the panel is set to 400 × 250 and the layout is computed, the values come out as follows. In the default font the buttons are 26 pixels high. North is 400 × 26 at (0, 0), and south is 400 × 26 at (0, 224). West and east start below north with a 5-pixel gap: y = 26 + 5 = 31. Their height is 250 − 26 − 26 − 2 × 5 = 188. West is 56 pixels wide and east 63; these are the widths that the texts “West” and “East” require. The center starts at x = 56 + 5 = 61 and is 400 − 56 − 63 − 2 × 5 = 271 pixels wide. The 76 pixels that the center prefers are not used at all in this calculation.

If the window is enlarged, the center grows the most. North and south only widen, and west and east only lengthen. This property makes BorderLayout suitable for the main window layout: a text area or a drawing canvas is put in the center and grows with the window.

Example 9.7

Five components are added to a 300 × 200 pixel BorderLayout panel with no gaps. The preferred sizes are: north 100 × 30, south 100 × 20, west 60 × 50, east 40 × 50, center 10 × 10. Then a second component with preferred size 80 × 40 is added to the north. What are the bounds of the components?

North takes the whole width; its height is the preferred 30: (0, 0, 300, 30). The preferred width of 100 is ignored. South is at the bottom: y = 200 − 20 = 180, so (0, 180, 300, 20). West and east take the height between them, 200 − 30 − 20 = 150 pixels: west (0, 30, 60, 150), east (300 − 40, 30, 40, 150) = (260, 30, 40, 150). The center takes the rest: (60, 30, 200, 150). The second north component replaces the first and is 40 pixels high. West, east, and center move down 10 pixels and become shorter: west (0, 40, 60, 140), center (60, 40, 200, 140). The old north component stays in the panel, but its size is not updated. The program run in headless mode gave all these values.

9.4.5GridLayout and BoxLayout

GridLayout(rows, columns) divides the container into cells of equal size. Components are placed row by row, from left to right. Each component completely fills its cell; the preferred size is ignored.

Example 9.8

Five buttons are added in order to a 300 × 120 pixel panel that uses new GridLayout(2, 3). What are the position and size of the fifth button?

The cell width is 300 / 3 = 100 and the height is 120 / 2 = 60. Buttons 1–3 fill the top row. Button 4 goes into the first cell of the bottom row and button 5 into the second cell: (100, 60, 100, 60). The sixth cell stays empty. The cell size does not change with the number of components; the program run gave the same bounds.

One of the row or column counts may be given as 0. new GridLayout(0, 2) means “two columns, as many rows as needed.” If five buttons are added to a 200 × 150 panel, three rows are formed. The cells are 100 × 50, and the fifth button is placed at (0, 100). If the number of components exceeds rows × columns and neither is zero, Java keeps the number of rows and increases the number of columns. When seven buttons are added to GridLayout(2, 3), the grid becomes 2 × 4 and the cells narrow to 75 pixels.

BoxLayout arranges components in a single row or a single column. Its constructor also takes the container it manages as a parameter: panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)). Y_AXIS stacks components vertically and X_AXIS places them side by side. It is used in forms to line up labels and fields one under another.

Common mistake

Setting a component's position with setBounds or setLocation in a container that has a layout manager. The manager overwrites these values at the next layout computation, and the position you set is lost. To influence a component's size, use setPreferredSize. The manager takes this preference into account or not, depending on its rule.

9.5Application: the no-entry sign

9.5.1Goal and layers

This application writes a panel that draws the “no entry” traffic sign. The sign consists of four layers painted on top of one another:

  1. A green background (with setBackground).
  2. A large white circle (the outer ring).
  3. A red circle, slightly smaller.
  4. A white horizontal bar in the middle.
Figure 9.16: The no-entry sign: a white ring, a red circle, and a white horizontal bar in the middle on a green background.

The program makes one important design decision: all measurements are computed from getWidth() and getHeight(). No fixed pixel values are used. When the window is enlarged, the sign grows with it and always stays in the center. The drawing is recomputed from scratch each time, according to the current size of the panel.

9.5.2The 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);
    }
}

The code computes five variables and then draws three shapes. The variables are declared with var. Since Java 10, var lets the compiler infer the type of a local variable from the expression on the right. Here the type of c is Point and the others are int. The classic form is Point c = new Point(…); int r = …;. var does not remove the type; the type is determined at compile time and never changes afterward.

Let us read the lines in order:

  • c: The center of the panel. The width and height are divided by two. Since both operands are int, integer division is used.
  • r: The radius of the outer circle. The distance from the center to the shorter side is chosen (Math.min), and a margin of 5 pixels is left. This way the circle does not spill outside the panel.
  • r2: The radius of the inner circle, 90% of r. r * 0.9 is a double; the (int) cast discards the fractional part.
  • bw and bh: The width and height of the bar, 1.4 and 0.35 times the inner radius.

The drawing is done in three steps. First the pen is switched to white and the outer circle is drawn. Then the pen is switched to red and the inner circle is drawn. The red circle is painted on top of the white one, so only a thin ring of white remains on the outside. Finally the pen is switched back to white and the bar is drawn. The bar is given by the top-left corner of its bounding rectangle: from the center, half the width to the left and half the height up.

The necessary imports are java.awt.* and javax.swing.*. Point, Graphics, and Color come from the first, and JPanel from the second.

9.5.3Code trace: drawing the sign

Let the panel be 384 × 261 pixels. This size is typical of the inner area left from a 400 × 300 window after the title bar and borders are subtracted. The real value varies by a few pixels depending on the operating system and theme settings.

Table 9.10: Trace of paintComponent for a 384 × 261 panel.
StepLineVariablesExplanation
11: super.paintComponent(g);getWidth()=384, getHeight()=261The panel is 384 × 261 pixels. super.paintComponent paints the background with the background color (green).
22: var c = new Point(getWidth() / 2, getHeight() / 2);getWidth()=384, getHeight()=261, c=(192, 130)Center: (384 / 2, 261 / 2) = (192, 130). Integer division: 130.5 → 130.
33: var r = Math.min(getWidth() / 2, getHeight() / 2) - 5;getWidth()=384, getHeight()=261, c=(192, 130), r=125Radius: min(192, 130) − 5 = 125. It is chosen by the shorter side, leaving a 5-pixel margin.
44: var r2 = (int) (r * 0.9);getWidth()=384, getHeight()=261, c=(192, 130), r=125, r2=112Inner radius: (int) 112.5 = 112.
55: var bw = (int) (r2 * 1.4);getWidth()=384, getHeight()=261, c=(192, 130), r=125, r2=112, bw=156Bar width: (int) (112 × 1.4) = (int) 156.8 = 156.
66: var bh = (int) (r2 * 0.35);getWidth()=384, getHeight()=261, c=(192, 130), r=125, r2=112, bw=156, bh=39Bar height: (int) 39.2 = 39.
77: g.setColor(Color.WHITE);
8: g.fillOval(c.x - r, c.y - r, 2 * r, 2 * r);
getWidth()=384, getHeight()=261, c=(192, 130), r=125, r2=112, bw=156, bh=39fillOval(67, 5, 250, 250): the white circle; its bounding square is the dashed line.
89: g.setColor(Color.RED);
10: g.fillOval(c.x - r2, c.y - r2, r2 * 2, r2 * 2);
getWidth()=384, getHeight()=261, c=(192, 130), r=125, r2=112, bw=156, bh=39fillOval(80, 18, 224, 224): the red circle is painted over the white one; a white ring 13 pixels thick remains.
911: g.setColor(Color.WHITE);
12: g.fillRect(c.x - bw / 2, c.y - bh / 2, bw, bh);
getWidth()=384, getHeight()=261, c=(192, 130), r=125, r2=112, bw=156, bh=39fillRect(114, 111, 156, 39): the white bar on top. The sign is complete.

In step 2, the center (384 / 2, 261 / 2) is computed. 261 / 2 is 130.5 in mathematics, but integer division discards the fraction: (192, 130). In step 3, the radius is found as min(192, 130) − 5 = 125. The shorter side is the height, so it determines the radius.

Steps 4–6 show type conversion. 125 × 0.9 = 112.5; (int) truncates it to 112. There is no rounding: even 112.5 goes down. 112 × 1.4 should be 156.8. double arithmetic cannot represent this value exactly; in Java the result of the product is 156.79999999999998. Truncation still gives 156. The bar height is 112 × 0.35 = 39.2; truncated, it is 39.

Figure 9.17: Step 8. fillOval(80, 18, 224, 224): the red circle has been painted over the white one; the bounding square is shown with a dashed line.

The arguments of the call fillOval(c.x − r, c.y − r, 2 * r, 2 * r) in step 7 are (192 − 125, 130 − 125, 250, 250) = (67, 5, 250, 250). In step 8 the inner circle is drawn with (192 − 112, 130 − 112, 224, 224) = (80, 18, 224, 224). The difference between the two radii, 125 − 112 = 13, gives the 13-pixel white ring. In step 9 the bar is drawn at (192 − 78, 130 − 19, 156, 39) = (114, 111, 156, 39). The values bw / 2 = 78 and bh / 2 = 19 are also integer divisions.

The computed calls were verified in Java. The panel was set to 384 × 261 in headless mode and paintComponent was run on an image with a DebugGraphics pen. The log showed exactly fillOval(67, 5, 250, 250), fillOval(80, 18, 224, 224), and fillRect(114, 111, 156, 39). The pixels in the image also had the expected colors: the center is white (the bar), (192, 25) is red, (192, 10) is white (the ring), and (5, 5) is green.

Example 9.9

If the same paintComponent runs on a 240 × 180 pixel panel, what are the variables and the arguments of the three drawing calls?

The center is (120, 90). r = min(120, 90) − 5 = 85. r2 = (int) (85 × 0.9) = (int) 76.5 = 76. bw = (int) (76 × 1.4) = (int) 106.4 = 106; bh = (int) (76 × 0.35) = (int) 26.6 = 26. Truncation lowers even 26.6 to 26. The calls are as follows:

setColor(0, 178, 0)
fillRect(0, 0, 240, 180)
setColor(255, 255, 255)
fillOval(35, 5, 170, 170)
setColor(255, 0, 0)
fillOval(44, 14, 152, 152)
setColor(255, 255, 255)
fillRect(67, 77, 106, 26)

The outer circle is (120 − 85, 90 − 85, 170, 170) and the inner circle is (120 − 76, 90 − 76, 152, 152); the ring is 9 pixels thick. For the bar, bw / 2 = 53 and bh / 2 = 13: (67, 77, 106, 26).

Example 9.10

If the panel were 200 × 100 pixels, what would r, r2, bw, and bh be?

r = min(100, 50) − 5 = 45. r2 = (int) 40.5 = 40. bw = (int) (40 × 1.4) and bh = (int) (40 × 0.35). A floating-point trap may come to mind here: 1.4 and 0.35 cannot be represented exactly in binary, so could the product come out as 55.999… and be truncated to 55? Tried in Java, 40 * 1.4 gave exactly 56.0 and 40 * 0.35 gave exactly 14.0. The result is bw = 56, bh = 14. In boundary cases like this, the way to trust the result is to run the calculation.

Common mistake

Mixing up the order of the layers. If the red circle is drawn before the white one, the large white circle covers it completely and the sign turns into a white disk. If the bar is drawn before the red circle, the red circle covers the bar. Whatever is drawn later is always on top; the drawing order is the layer order.

9.5.4main 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);
    });
}

The only job of the main method is to hand the code that builds the interface to SwingUtilities.invokeLater. () -> { … } is a lambda expression: “a piece of code to be run later.” invokeLater puts this piece in a queue to be run on the event dispatch thread. This pattern appears in the main of every Swing program; the reason lies in how the event dispatch thread works.

Inside the lambda, the panel is created and its background is set to Color.GREEN.darker(), that is, (0, 178, 0). Pure green (0, 255, 0) is bright enough to strain the eyes; the darker shade looks more like a traffic sign. super.paintComponent(g) paints the background with this color. The panel is added to the center of the window's content pane. Since it is the only component, it fills the whole area.

In a 400 × 300 window, after the border and title bar are subtracted, the panel is about 384 × 261. This value varies with the operating system. The program's correctness does not depend on it: the measurements are recomputed from getWidth() and getHeight() at every painting. If the panel is enlarged to 768 × 522, the outer circle is drawn with fillOval(128, 5, 512, 512) and the sign is still in the center.

9.6Mouse events and the event dispatch thread

9.6.1Interactive graphics and the event loop

Computer graphics is the process of creating and manipulating visual content. In interactive graphics, the user changes the image with input devices such as the mouse and keyboard. Drawing programs, games, and maps are of this kind. Graphics libraries provide drawing and coloring shapes; interaction is built with an event loop.

Usermouse, keyboardOperating systeminput device signalEvent queueMouseEvent, KeyEvent…Event dispatch thread(EDT) takes the next eventListener methodmousePressed(e)…repaint()repaint requestpaintComponent(g)called by SwingScreenup-to-date picturenext event
Figure 9.18: The event loop. The user's action passes through the operating system and enters the event queue. The event dispatch thread hands the event to the listener method; the method updates the data and requests a repaint(). At a suitable moment Swing calls paintComponent and the screen is updated.

The steps in the loop are as follows. The user presses the mouse. The operating system detects this action and notifies Java. Java creates an event object and puts it in the event queue. The event dispatch thread takes the next event in the queue and calls the method of the listener registered with that component. The listener method updates the program's data and requests a redraw with repaint(). At a suitable moment Swing calls paintComponent, and the screen is drawn with the new data. The event dispatch thread moves on to the next event.

This loop has a rule: a listener method does not paint the screen directly. It only changes the data and requests a repaint. The drawing is always done by paintComponent. This separation keeps the drawing in one place and ensures that the correct picture appears every time the window is repainted.

9.6.2Listener interfaces and adapter classes

Definition 9.11

An event listener is an interface that defines the methods to be called when an event occurs, or an object that implements this interface. A listener object is registered with a component using an add…Listener method.

For mouse events, Java's interface is MouseListener. The interface has five abstract methods. If a class implements this interface, it must write all five methods. The bodies of the methods it is not interested in stay empty.

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) { }
}

Four of the five methods are empty. For a class interested only in clicks, this is extra typing. Java offers ready-made classes for this situation.

Definition 9.12

An adapter class is a ready-made class that implements all the methods of a listener interface with empty bodies. A class derived from it overrides only the method it is interested in.

class ClickAdapter extends MouseAdapter {
    @Override
    public void mouseClicked(MouseEvent e) {
        System.out.println("click");
    }
}
// panel.addMouseListener(new ClickAdapter());

MouseAdapter is an abstract class, but it has no abstract methods; all its methods have empty bodies. The purpose of declaring it abstract is to prevent creating an object of it directly. MouseAdapter implements three interfaces at once: MouseListener, MouseMotionListener, and MouseWheelListener. A single subclass can thus handle click, motion, and wheel events.

Motion events are in a separate interface: MouseMotionListener. This interface has two methods: mouseDragged and mouseMoved. Its own adapter is MouseMotionAdapter. Registration is separate too: click-type events are registered with addMouseListener(…) and motion events with addMouseMotionListener(…).

The listener class does not even need to be written in a separate file. Java allows a single-use class to be defined where it is used.

Definition 9.13

An anonymous inner class is an inner class that has no name and whose single object is created where it is defined. The notation new MouseAdapter() { … } defines a nameless class derived from MouseAdapter and immediately creates an object of it.

Common mistake

Implementing an interface and not writing some of its methods. If class ClickListener implements MouseListener writes only mouseClicked, the compiler gives this error:

ClickListener.java:6: error: ClickListener is not abstract and does not override abstract method mouseExited(MouseEvent) in MouseListener
class ClickListener implements MouseListener {

The compiler names only one of the missing methods. Even if mousePressed is written too, the message still points to mouseExited; the message is not a list of the missing methods. The solution is either to write all five methods or to derive from MouseAdapter.

9.6.3Mouse event methods

Table 9.11: 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)MouseListenerWhen pressed and released at the same place (pressed → released → clicked)
mouseEntered(e) / mouseExited(e)MouseListenerWhen the pointer enters / leaves the component
mouseMoved(e)MouseMotionListenerWhen it moves without a button pressed
mouseDragged(e)MouseMotionListenerWhen it moves while a button is held down (dragging)
mouseWheelMoved(e)MouseWheelListenerWhen the wheel is turned
click:mouseEnteredmousePressedmouseReleasedmouseClickedmouseExiteddragging: mousePressed → mouseDragged … → mouseReleased; no mouseClicked, because the pointer has moved
Figure 9.19: The order of mouse events. A click produces three events; a drag produces many mouseDragged events between the press and the release.

A click is not a single event. The user presses the button: mousePressed. The user releases it: mouseReleased. If the press and the release were at the same point, Java also generates a mouseClicked. If the mouse moved between the press and the release, no mouseClicked arrives; mouseDragged events come in between. That is why applications such as a drawing program listen not for clicks but for presses and drags.

When press, release, and click events were sent in turn to a panel in headless mode, the listeners were called in this order. Because both ClickListener (which implements the interface) and ClickAdapter (derived from the adapter) were registered with the same panel, “click” was printed twice on a click. Several listeners can be registered with one component; when an event arrives, all of them are called.

9.6.4The MouseEvent class

Every mouse method takes a MouseEvent e parameter. Where the event happened, with which button, and with which keys held down is all in this object.

Table 9.12: Frequently used methods of the MouseEvent class.
MethodReturns
getX(), getY()The pointer's position relative to the component
getPoint()The same position, as a Point
getButton()BUTTON1 left, BUTTON2 middle, BUTTON3 right (the values 1, 2, 3)
getClickCount()The number of consecutive clicks (2: double click)
isShiftDown(), isCtrlDown(), isAltDown()Is the key held down at that moment?
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" : ""));
    }
});

The code registers an anonymous adapter with a panel. If the pressed button is the right button, the variable button becomes “right.” Then the button name, the position, and, if the Shift key is held down, “ + Shift” are printed. Running it showed that a left click at (40, 120) on the panel prints left (40, 120), and a right click at (70, 30) with Shift held down prints right (70, 30) + Shift.

Coordinates are relative not to the screen but to the component that received the event. The top-left corner of a panel is (0, 0) wherever the panel is in the window. This makes it possible to compare mouse coordinates directly with the shapes drawn inside the panel.

In short, a click produces three events in the order pressed → released → clicked; while dragging, many mouseDragged events arrive. The right button is BUTTON3.

9.6.5The event dispatch thread (EDT)

The main of a Swing program is written with the SwingUtilities.invokeLater pattern. The reason for this pattern is Swing's relationship with threads.

Definition 9.14

The event dispatch thread (EDT) is the single thread on which Swing components are built and modified and on which events are processed. It runs the tasks in the event queue one at a time, in order. In Java 21 its name is AWT-EventQueue-0.

Swing components are not thread-safe. If several threads touch the same component at the same time, the internal state of the component can become inconsistent. Swing solves this problem not with locks but with a simple rule: components are built and modified only from the event dispatch thread. Listener methods already run on the EDT, so it is safe to touch components from inside them.

An analogy explains the rule. In the kitchen there is a single cook: the EDT. The waiters do not cook the food themselves; they leave an order slip. The slip is a Runnable object, that is, a piece of code to be run. The cook prepares the slips one at a time, in the order they arrive. Since there is only one cook, two dishes never enter the same pan at the same time.

main threadmain endsinvokeLater(task)event queuetaskmousekeypaintevent dispatch thread (EDT)runs them one at a time, in orderlasts until the window closes
Figure 9.20: The main thread puts a task in the event queue with invokeLater and finishes. The event dispatch thread runs the tasks in the queue in order.
Table 9.13: The two invocation methods of SwingUtilities.
MethodBehavior
invokeLater(task)Puts the task in the queue and returns immediately (asynchronous). The standard way to start a GUI.
invokeAndWait(task)Waits until the task finishes on the EDT (synchronous). If called from inside the EDT, it throws an Error: the EDT cannot wait for itself.

Calling invokeAndWait from inside the EDT really does throw an Error. If the EDT waited for a task it had itself put in the queue, nobody would be left to run that task, and the program would hang forever. Swing catches this in advance:

AWT-EventQueue-0 daemon=false
java.lang.Error: Cannot call invokeAndWait from the event dispatcher thread

The first line shows which thread the task run with invokeAndWait is on: AWT-EventQueue-0. This thread is not a daemon (background) thread. The JVM does not exit while a non-daemon thread is running. This is why a GUI program continues after main ends.

9.6.6Code trace: 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());
}
1 main
2 main goes on
3 task A
4 task B
5 task C, EDT? true
6 main, EDT? false
Table 9.14: Trace of the event queue.
StepLineVariablesNew output
12: System.out.println("1 main");thread=main1 main
23: SwingUtilities.invokeLater(
4: () -> System.out.println("3 task A"));
queue=[A]—
35: SwingUtilities.invokeLater(
6: () -> System.out.println("4 task B"));
queue=[A, B]—
47: System.out.println("2 main goes on");queue=[A, B]2 main goes on
58: SwingUtilities.invokeAndWait(() -> System.out.println(
9: "5 task C, EDT? " + SwingUtilities.isEventDispatchThread()));
queue=[A, B, C]—
64: () -> System.out.println("3 task A"));queue=[B, C]3 task A
76: () -> System.out.println("4 task B"));queue=[C]4 task B
88: SwingUtilities.invokeAndWait(() -> System.out.println(
9: "5 task C, EDT? " + SwingUtilities.isEventDispatchThread()));
queue=[]5 task C, EDT? true
910: System.out.println("6 main, EDT? "
11: + SwingUtilities.isEventDispatchThread());
thread=main6 main, EDT? false

The program starts on the main thread and prints 1 main. In step 2, invokeLater puts task A in the queue and returns immediately. If the event dispatch thread does not exist yet, this first call starts it. In step 3, task B is also added to the queue; main still does not wait. In step 4, main continues with its own work and prints 2 main goes on.

mainevent queueEDTwaitinguntil task C finishesABCfirst in, first outempty
Figure 9.21: Step 5. invokeAndWait has put task C in the queue and stopped main. A, B, and C are waiting in the queue.

In step 5, invokeAndWait puts task C in the queue and stops main. The EDT processes the queue from the beginning: first A (3 task A), then B (4 task B), then C. The queue is ordered; tasks run in the order they entered it. Task C asks which thread it is on with isEventDispatchThread() and gets true. When C finishes, the waiting main is woken up. In the last line, main asks the same question and gets false.

We must be careful about the order of the output. The order 1, 2, 3, 4, 5, 6 was seen in this run. When the program was run 20 times, the order was the same each time. But part of the order is not guaranteed. The line 2 main goes on and the line 3 task A come from different threads. The EDT could have run A before main printed line 2. What is certain is this: A runs before B, B before C, and C before 6. The same distinction applies to the sequence invokeLater(B), println(A), invokeAndWait(C), println(D). B comes before C and C before D. In 20 trials ABCD was always seen, but the places of A and B may change from run to run.

Example 9.11

A button listener runs System.out.println("1"), SwingUtilities.invokeLater(() -> System.out.println("3")), and System.out.println("2") in that order. What is the output? Is the order certain?

1, 2, 3. The listener runs on the EDT. invokeLater puts the task at the end of the queue and returns; the listener prints 2 and finishes. Only after that can the EDT take the next task in the queue. This time the order is certain, because both pieces run on the same thread. A task put in the queue cannot start before the task that is currently running.

Common mistake

Building the interface directly on the main thread. In small programs this often causes no problem, so the mistake goes unnoticed for a long time. But once the window becomes visible, the EDT starts running and can touch the same components as main. The result is rare, random drawing glitches or exceptions. There is only one safe pattern: SwingUtilities.invokeLater(() -> { … }).

9.7Application: a drawing program

This application is a program in which you draw by pressing and dragging the mouse. The principle is summarized in three sentences:

  • On a press (mousePressed), a new curve starts.
  • As the mouse is dragged (mouseDragged), points are added to the end of the curve and a repaint is requested.
  • When painting (paintComponent), the consecutive points of each curve are joined with lines.
Figure 9.22: A panel on which you draw with the mouse.

The basic design decision of the program is to store the drawing not as an image but as a list of points. The screen is redrawn from this data each time. The drawing is not lost even if the window is minimized and restored, or another window passes over it and is dragged away. Separating the data from the picture applies the rule of the event loop: listeners change the data, and paintComponent draws the data.

9.7.1Storing the curves

public class SimpleDrawPanel extends JPanel {
    private List<List<Point>> curves = new ArrayList<>();

    public SimpleDrawPanel() {
        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());
            }
        });
    }
}

The class's only field is curves. Its type is List<List<Point>>, a list of lists. The outer list holds the curves. Each inner list holds the points of one curve in order.

curve 0:(40,120)(60,60)(80,120)curve 1:(50,95)(70,95)
Figure 9.23: A drawing with two curves and the data that holds it. Curve 0 consists of three points and curve 1 of two.

The constructor registers two listeners. The first is an anonymous class derived from MouseAdapter that writes only mousePressed. The method creates a new, empty list of points, adds the pressed point to the list, and puts the list in the outer list. The second listener is derived from MouseMotionAdapter and writes only mouseDragged. The method takes the last element of the outer list, that is, the most recently started curve, and appends the new point to it. Then it has the panel repainted.

The last curve is reached with curves.get(curves.size() - 1). Since list indices start at 0, the index of the last element is size() - 1. get(size()) always asks for one position past the end of the list.

Common mistake

Asking for the last element with get(size()). When the list holds one curve, this call throws the following exception:

java.lang.IndexOutOfBoundsException: Index 1 out of bounds for length 1

The error is not caught at compile time; it appears on the first drag. The correct index is size() - 1.

The code has an import trap as well. If java.awt.* and java.util.* are imported together, the name List exists in both packages: java.awt.List is a list-box component, whereas java.util.List is the collection interface. The compiler cannot tell which one is meant:

Main.java:4: error: reference to List is ambiguous
  List<String> x;
  both interface java.util.List in java.util and class java.awt.List in java.awt match

The solution is to import the intended class explicitly as well: import java.util.List;. A single-type import takes precedence over an on-demand (star) import.

9.7.2Code trace: mouse events

Suppose the user makes the following moves: presses at (40, 120), drags to (60, 60) and (80, 120), and releases; then presses again at (50, 95) and drags to (70, 95).

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());
    }
});
Table 9.15: Trace of the mouse events.
StepLineVariablesExplanation
14: var curve = new ArrayList<Point>();
5: curve.add(new Point(e.getX(), e.getY()));
6: curves.add(curve);
e.getX()=40, e.getY()=120, curves.size()=1mousePressed: Pressed at (40, 120): a new inner list is created, its first point is added, and it is put in the outer list.
212: curves.get(curves.size() - 1)
13: .add(new Point(e.getX(), e.getY()));
14: repaint(0, 0, getWidth(), getHeight());
e.getX()=60, e.getY()=60, curves.size()=1mouseDragged: Dragged to (60, 60): a point is added to the last curve; repaint requests a redraw, and the line appears.
312: curves.get(curves.size() - 1)
13: .add(new Point(e.getX(), e.getY()));
14: repaint(0, 0, getWidth(), getHeight());
e.getX()=80, e.getY()=120, curves.size()=1mouseDragged: Dragged to (80, 120): the same curve gets longer. In reality dozens of mouseDragged events arrive per second.
41: addMouseListener(new MouseAdapter() {e.getX()=80, e.getY()=120, curves.size()=1mouseReleased: Released: we did not write mouseReleased; the empty body of MouseAdapter runs and nothing happens.
54: var curve = new ArrayList<Point>();
5: curve.add(new Point(e.getX(), e.getY()));
6: curves.add(curve);
e.getX()=50, e.getY()=95, curves.size()=2mousePressed: Pressed again at (50, 95): the second curve starts. The old curve stays as it is.
612: curves.get(curves.size() - 1)
13: .add(new Point(e.getX(), e.getY()));
14: repaint(0, 0, getWidth(), getHeight());
e.getX()=70, e.getY()=95, curves.size()=2mouseDragged: Dragged to (70, 95): the point is again added to the last curve, that is, curve 1.

In step 1 the outer list is empty. mousePressed creates a new inner list, adds (40, 120), and puts the inner list in the outer list: curves.size() becomes 1. In steps 2 and 3, mouseDragged adds two points. Both go to the last curve, that is, curve 0. After each addition, repaint requests a redraw and the new line segment appears on the screen.

In real use the number of events is much larger. As the mouse moves, the operating system reports dozens of positions per second, and each becomes a mouseDragged. The two drags in the trace are two samples from this stream.

In step 4 the user releases the mouse. We did not write mouseReleased. The event still arrives, but the empty body of MouseAdapter runs and nothing happens. In step 5, a new press starts a second inner list; the old curve stays as it is. The drag in step 6 is again added to the last curve, now curve 1.

The event sequence was tried by sending it directly to the panel in headless mode. The data written after each step gave the final state of the table: [[(40,120), (60,60), (80,120)], [(50,95), (70,95)]].

9.7.3Code trace: drawing the curves

@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;
        }
    }
}

The method uses two nested loops. The outer loop goes over the curves and the inner loop over the points of one curve. The variable prev holds the point where the line will start. At the beginning of each curve, prev is set to the first point of that curve. At each point the inner loop draws a line from prev to that point and advances prev.

Table 9.16: Trace of paintComponent; the “New output” column is the drawing call made.
StepLineVariablesNew output
13: super.paintComponent(g);——
24: for (var c : curves) {
5: var prev = c.get(0);
c=curve 0, prev=(40,120)—
36: for (var p : c) {
7: g.drawLine(prev.x, prev.y, p.x, p.y);
8: prev = p;
c=curve 0, prev=(40,120), p=(40,120)drawLine(40, 120, 40, 120)
46: for (var p : c) {
7: g.drawLine(prev.x, prev.y, p.x, p.y);
8: prev = p;
c=curve 0, prev=(40,120), p=(60,60)drawLine(40, 120, 60, 60)
56: for (var p : c) {
7: g.drawLine(prev.x, prev.y, p.x, p.y);
8: prev = p;
c=curve 0, prev=(60,60), p=(80,120)drawLine(60, 60, 80, 120)
64: for (var c : curves) {
5: var prev = c.get(0);
c=curve 1, prev=(50,95)—
76: for (var p : c) {
7: g.drawLine(prev.x, prev.y, p.x, p.y);
8: prev = p;
c=curve 1, prev=(50,95), p=(50,95)drawLine(50, 95, 50, 95)
86: for (var p : c) {
7: g.drawLine(prev.x, prev.y, p.x, p.y);
8: prev = p;
c=curve 1, prev=(50,95), p=(70,95)drawLine(50, 95, 70, 95)

One detail stands out in step 3. The inner loop starts at the first point, and prev is also the first point. The first call is drawLine(40, 120, 40, 120): the point is joined to itself, and a single pixel is drawn. Then prev = p is executed. The next two calls draw the real lines: (40,120) → (60,60) and (60,60) → (80,120).

Figure 9.24: Step 8. The drawing is complete after five drawLine calls; the two curves are not joined to each other.

In the next step the outer loop moves on to the second curve, and prev again becomes the first point of this curve. This line is what keeps the two curves from joining. If prev were not reset for each curve, an unwanted line would be drawn between the last point of curve 0, (80, 120), and the first point of curve 1, (50, 95). The total number of calls is 3 + 2 = 5; the number of visible line segments is 2 + 1 = 3.

The DebugGraphics log gave the same five calls:

setColor(238, 238, 238)
fillRect(0, 0, 200, 200)
drawLine(40, 120, 40, 120)
drawLine(40, 120, 60, 60)
drawLine(60, 60, 80, 120)
drawLine(50, 95, 50, 95)
drawLine(50, 95, 70, 95)

Again, super.paintComponent(g) produced the first two lines: the background was cleared with the panel's background color. No trace of the earlier drawing remains. The new picture is built each time from an empty background and the whole of the data.

Example 9.12

The user presses at (10, 10), drags to (20, 10) and (30, 20), and releases; then presses at (5, 5), drags to (6, 6), and releases. What are curves.size(), the number of points in each curve, and the number of drawLine calls when repainting?

Each press adds an inner list, so curves.size() is 2. Curve 0 has three points and curve 1 has two. The number of drawLine calls equals the number of points: 3 + 2 = 5. The log is as follows:

setColor(238, 238, 238)
fillRect(0, 0, 200, 200)
drawLine(10, 10, 10, 10)
drawLine(10, 10, 20, 10)
drawLine(20, 10, 30, 20)
drawLine(5, 5, 5, 5)
drawLine(5, 5, 6, 6)

9.7.4main and repaint

public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> {
        var frame = new JFrame("Simple Drawing Program");
        frame.getContentPane().add(new SimpleDrawPanel(),
                BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.setVisible(true);
    });
}

main follows the familiar pattern: the interface is built on the EDT with invokeLater, the panel is added to the center of the content pane, and the window is shown at 400 × 300.

The repaint method is used in two forms, and both are only requests:

  • repaint() does not paint immediately; it puts a “repaint” request in the queue. Consecutive requests can be merged into a single painting. While the mouse produces dozens of events per second, this merging prevents unnecessary drawing.
  • repaint(x, y, w, h) asks for only that rectangle to be repainted. Swing clips everything outside this region: g does not paint outside the region, and the work is reduced. repaint(0, 0, getWidth(), getHeight()) is the same as repaint().
Definition 9.15

repaint() is the method that leaves a request in the event queue for a component to be redrawn. At a suitable moment Swing calls the component's paintComponent method. The programmer does not call paintComponent directly; the programmer changes the data and requests repaint().

Common mistake

Calling paintComponent(getGraphics()) from inside a listener. This call bypasses Swing's painting machinery. Double buffering, that is, preparing the image in memory first, is switched off, and the picture may flicker. At the next real painting, everything drawn is erased as well. The correct way is repaint().

9.8Buttons and text components

9.8.1The JButton class

JButton creates clickable buttons. Its text is set with setText() and its icon with setIcon(). setEnabled(false) disables the button: it looks faded and produces no event when clicked.

To respond to a click on a button, a listener is added with addActionListener(). The listener implements the ActionListener interface. This interface has a single method: actionPerformed(ActionEvent e). A button can also be triggered with the space bar; the same method is called in both cases. That is why we listen for an “action” event, not a mouse event, on a button.

Adding a listener is an example of the Observer design pattern. The button is the “subject”; it keeps a list of the observers registered with it. When a click occurs, it notifies every observer in the list. The button does not know what the observers do. To add new behavior, you do not need to touch the button's code; you only register a new observer.

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

9.8.2Code trace: the counter button

Table 9.17: Trace of the counter button.
StepLineCall stackVariablesExplanation
12: private int count = 0;
3: private JLabel label = new JLabel("Not clicked yet");
main() → new CounterPanel()count=0, label=JLabelWhen the object is created, the fields get their initial values first: count is 0 and the label is ready.
26: JButton button = new JButton("Click");main() → CounterPanel()button=JButton("Click")The constructor creates a button; button is a local variable.
37: button.addActionListener(e -> {
8: count++;
9: label.setText(count + " click(s)");
10: });
main() → CounterPanel()listener count=1The lambda is not run; it is only registered with the button. Its body will run on a click.
411: add(button);
12: add(label);
main()component count=2The button and the label are added to the panel (FlowLayout: side by side). The constructor ends.
58: count++;EDT → actionPerformed(e)count=1The user clicks: the EDT calls actionPerformed, that is, the lambda body. count can be incremented because it is a field.
69: label.setText(count + " click(s)");EDT → actionPerformed(e)count=1setText changes the text of the label; Swing repaints the label.
78: count++;EDT → actionPerformed(e)count=2The second click: the same lambda is called again, and the field becomes 2.
89: label.setText(count + " click(s)");EDT → actionPerformed(e)count=2The label is updated. Between clicks the program runs no code at all; it only waits for events.

In step 1, new CounterPanel() starts to run. Before the body of the constructor, the fields get their initial values: count becomes 0 and label is created with the text “Not clicked yet.” In step 2, the constructor creates a button. button is a local variable; it disappears when the constructor ends, but the button itself lives on as a component of the panel.

Step 3 is the most important step of the trace. The lambda expression is not run at this point. It is only registered with the button as an object. count++ and setText in its body will run only when the button is clicked. In step 4, the button and the label are added to the panel. FlowLayout places them side by side. The constructor ends; the panel has 2 components and the button has 1 listener.

CounterPanel objectcount1labelJLabelcomponents: 2JButton "Click"listeners: 1lambda e -> {…}accesses the fields count and labelon screen:Not clicked yet
Figure 9.25: Step 5. The user has clicked; the EDT called the actionPerformed of the listener registered with the button, that is, the lambda body.

In step 5 the user clicks. The EDT calls actionPerformed, that is, the lambda body. count can be incremented because it is a field: it becomes 1. In step 6, setText changes the label's text to “1 click(s)” and Swing repaints the label. Steps 7 and 8 are the second click: the same lambda is called again, the field becomes 2, and the label is updated.

Between clicks the program runs no code; it only waits for events. This behavior is very different from the continuously running flow of a console program. When a panel was created in headless mode and two clicks were given with the button's doClick method, the label became “1 click(s)” and “2 click(s)”. When the button was disabled with setEnabled(false) and clicked again, the label did not change.

2 1 Not clicked yet
1 click(s)
2 click(s)
disabled: 2 click(s)

9.8.3Anonymous classes and lambdas

The same listener can be written in two forms. The classic form is an anonymous inner class:

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        count++;
        label.setText("Count: " + count);
    }
});

Since Java 8, the same job can be written with a lambda expression:

button.addActionListener(e -> {
    count++;
    label.setText("Count: " + count);
});

// one expression: no braces needed
button.addActionListener(e -> System.exit(0));

A lambda can be used because of the structure of ActionListener: the interface has only one abstract method.

Definition 9.16

A functional interface is an interface with a single abstract method. A lambda expression is taken as the body of the single method of such an interface: e -> … is the body of actionPerformed(e).

The compiler looks at the parameter type of addActionListener, sees ActionListener, and finds its single method. The lambda's parameter e becomes the ActionEvent parameter of that method. If the body is a single expression, the braces are not needed either: button.addActionListener(e -> System.exit(0));.

Since MouseListener has five methods, it cannot be written as a lambda. The compiler cannot tell which method's body is being written:

Main.java:9: error: incompatible types: MouseListener is not a functional interface
  p.addMouseListener(e -> System.out.println("click"));
    multiple non-overriding abstract methods found in interface MouseListener

That is why an adapter class is used for mouse events.

A lambda has one more limitation: a local variable cannot be modified from inside it. A lambda captures (copies) the value of the local variable it uses; it is not bound to the variable itself. For this reason a local variable must be final or “effectively final,” that is, never changed after it is defined.

Common mistake

Keeping the counter in a local variable: int count = 0; … b.addActionListener(e -> count++);. The compiler gives this message:

Main.java:10: error: local variables referenced from a lambda expression must be final or effectively final
  b.addActionListener(e -> count++);

Changing values such as a counter must be fields of the class. Fields belong to the object; the lambda holds a reference to the object and can change the field. The counter panel therefore uses the field private int count.

9.8.4JLabel and JTextField

JLabel is a label. It displays text or an image; the user cannot change it. setText() sets the text, setIcon() the image, setFont() the font, and setForeground() the text color.

JTextField is a single-line text field. It is for the user to enter text; data from forms is collected this way. getText() and setText() read and write the field. setColumns() sets the number of visible columns. This number affects the preferred width of the field; it does not limit the length of text it can hold. In headless mode, a 12-column field asked for a width of 136 pixels and a 24-column field for 268. A listener added with addActionListener() runs when the user presses Enter in the field.

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() + "!"));

The code creates two labels and a text field. The first label is bold, 14-point, and blue. The text field is 12 columns wide. The second label initially contains a space: the preferred size of a label with empty text is 0 × 0, whereas a label with a single space takes up 3 × 16 pixels and reserves the greeting's row from the start. The listener reads the text in the field when Enter is pressed and writes it to the greeting label. In headless mode, when “Ayşe” was typed into the field and an Enter event was generated, the greeting label became Hello, Ayşe!.

Inside the lambda, the local variables nameField and greeting are used. Because these variables are not modified after they are defined, they are effectively final, and the lambda can capture them. The contents of the object a variable refers to may change; greeting.setText(…) is an example. The rule only forbids redirecting the variable to another object.

9.8.5JTextArea and JScrollPane

JTextArea is a multi-line text area. Its content can be read, assigned, and updated. The visible size is given in advance with new JTextArea(rows, columns). Its commonly used methods are: getText(), setText(), append() (adds at the end), setEditable(false) (makes it read-only), and setLineWrap(true) (wraps long lines).

JScrollPane is a scroll pane. When the component placed in it (a text area, a table, an image) does not fit on the screen, it adds scroll bars. It adapts itself when the size of the content changes. Its own size is set with setPreferredSize() and its content with setViewportView(). The text area is given to the scroll pane in the constructor, and it is the scroll pane, not the text area, that is added to the window.

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

setText deletes the old content and writes the new; append adds at the end. The text becomes "First line\nSecond line\n". getLineCount() returns one more than the number of line breaks: the text has two line breaks, so the result is 3. The third line is empty, but it is counted because the caret can be placed there. Even in an empty text area, getLineCount() is 1.

Example 9.13

Which three lines does the following code print?

JTextArea a = new JTextArea("x");
a.append("\ny");
a.append("\n");
System.out.println(a.getLineCount());
a.setText("one");
a.append(" line");
System.out.println(a.getText() + " " + a.getLineCount());
JTextField f = new JTextField(10);
f.setText(" 42 ");
System.out.println(Integer.parseInt(f.getText().trim()) + 1);

The text becomes "x\ny\n": two line breaks, three lines. The first line is 3. setText deletes the old content and append adds: "one line", with no line break, so the line count is 1. getText() always returns a String. trim() removes the leading and trailing spaces; 42 + 1 = 43. If the spaces had not been removed, parseInt would have thrown this exception: NumberFormatException: For input string: " 42 ".

3
one line 1
43

9.9Application: a text converter

This application converts the text in a text area to lowercase or uppercase with two buttons. The layout of the window is a good example of using two layout managers together:

  • In the center (CENTER) there is a JTextArea of 8 rows × 50 columns inside a JScrollPane.
  • At the bottom (SOUTH) there is a JPanel holding two buttons. Since the panel uses FlowLayout, the buttons are centered and side by side.
  • pack() computes the window size from the preferred sizes of these components.
  • The buttons convert the text with toLowerCase() or toUpperCase() and write it back to the area.
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 interface is built inside a single lambda, on the EDT. First the text area and the two buttons are created. A listener is added to each button. The listener reads the text of the area, converts it, and writes the result back to the area. Then the buttons are put in a panel. The window is created, the scroll pane is added to the center and the button panel to the south. pack() computes the size, and the window is shown.

The code has three details:

  • area is a local variable, but it can be used inside the lambda. After it is defined, the variable is never redirected to another object; it is effectively final. The lambda uses not the variable area itself but the object it refers to, and it changes the text of that object.
  • toUpperCase() returns a new String. Since String is immutable, the original text does not change; the result must be written back to the area with setText. If area.getText().toUpperCase(); were written alone, nothing on the screen would change.
  • BorderLayout.CENTER is written with its full name. Writing only CENTER does not compile, because the constant is inside the BorderLayout class.

When the same two buttons and a text area were created in headless mode and the buttons were pressed with doClick, the text turned first to uppercase and then to lowercase:

JAVA PROGRAMMING
java programming
default locale tr_TR: İSTANBUL / ENGLISH ISTANBUL / tr İSTANBUL

9.9.1What happens on a click?

Between the user's click on the “To Uppercase” button and the text changing on the screen, there are six steps.

  1. The user clicks the button; the operating system passes this to Java.
  2. Java creates an event object and puts it in the event queue.
  3. The EDT takes the next event. The button calls actionPerformed of all registered ActionListeners: our lambda runs.
  4. area.getText() reads the current text.
  5. toUpperCase() produces a new string; the old string does not change.
  6. setText updates the model of the area. The area has itself repainted with repaint. The EDT moves on to the next event.
User clicksTo UppercaseEvent queueActionEvent waitsEDTJButton receives the eventLambda: getText()"Java Programming"toUpperCase()new StringsetText + repaintscreen is updatedarea: Java Programming
Figure 9.26: Step 3. The EDT took the event from the queue and called the listener registered with the button.

Step 6 mentions the word “model.” In Swing, text components consist of two parts: a model that holds the text and a view that displays it on the screen. setText changes the model; the view notices the change and has itself redrawn. The change calculator application uses this separation directly.

9.9.2Uppercase and locale

When toUpperCase() and toLowerCase() are called without arguments, they use the computer's locale. Turkish is one of the languages with special rules for letter case conversion: there are two separate letters “i,” dotted and dotless. On a machine with English settings, "istanbul".toUpperCase() gives "ISTANBUL"; with Turkish settings it gives "İSTANBUL". The same program gives different results depending on the computer it runs on.

To fix the result, the locale is given explicitly: toUpperCase(Locale.forLanguageTag("tr")). The following experiment compares the rules of the two languages.

String s = "Kış İzmir";
Locale tr = Locale.forLanguageTag("tr");
System.out.println(s.toUpperCase(tr));
System.out.println(s.toLowerCase(tr));
System.out.println(s.toUpperCase(Locale.ENGLISH));
System.out.println(s);
KIŞ İZMİR
kış izmir
KIŞ İZMIR
Kış İzmir

In Turkish rules, i → İ, ı → I, İ → i, and I → ı. In English rules, both ı and i become I in uppercase, while İ stays as it is. That is why the third line is KIŞ İZMIR. The last line shows once more that strings are immutable: after the three conversions, s is still "Kış İzmir".

A locale object used to be created with new Locale("tr"). This constructor has been deprecated since Java 19, and the compiler gives a warning. Use Locale.forLanguageTag("tr") or Locale.of("tr") instead.

Common mistake

Basing the logic of a program on a locale-dependent conversion. For example, if a command is checked with command.toUpperCase().equals("QUIT"), on a machine with Turkish settings "quit" becomes "QUİT" and the comparison fails. For internal strings that are not shown to the user, give Locale.ROOT or Locale.ENGLISH; for Turkish text shown to the user, give the Turkish locale.

9.10Application: a change calculator

This application shows how an entered number of cents can be paid with the fewest coins (50, 25, 10, 5, and 1 cent). The window has no button: the report is updated automatically on every keystroke. This is provided by a DocumentListener added to the document of the text field.

9.10.1Fields 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(); }
        });
    }

This time the class derives not from JPanel but from JFrame. The window itself is the application. There are three fields: an amount field of 12 columns, the document of this field, and a report area of 8 rows × 40 columns.

In Swing, data and view are separate. This arrangement is called Model-View-Controller (MVC). JTextField is the view: it shows the text on the screen and receives what the user types. The Document object obtained with getDocument() is the model that holds the text. When the user presses a key, the model changes and everyone listening to the model is notified.

The constructor builds the top panel: an “Amount:” label and the amount field. The panel is added to the north of the window and the report area, inside a scroll pane, to the center. The report is made read-only. Finally an anonymous DocumentListener is added to the document.

DocumentListener has three methods: insertUpdate (text was inserted), removeUpdate (text was removed), and changedUpdate (style changed). In a plain text field there is no style, so changedUpdate is never called. But all three methods of the interface are abstract, and all three must be written. All three do the same thing: they call updateReport().

9.10.2Code trace: updateReport

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());
    }
}

The method reads the text of the document and converts it to an integer. doc.getText(0, doc.getLength()) returns the text of the document starting at character 0 and extending over its whole length. Then the coin values are put in an array from largest to smallest. The report is restarted from scratch with setText. For each coin value, the loop does two things: it prints how many of that coin will be used (amount / x) and computes the remaining amount (amount %= x).

Table 9.18: Trace of updateReport for the amount 93.
StepLineVariablesNew output
13: var amount = Integer.parseInt(
4: doc.getText(0, doc.getLength()));
amount=93—
25: int[] coins = {50, 25, 10, 5, 1};amount=93, coins=[50, 25, 10, 5, 1]—
36: report.setText(amount
7: + " cents in coins:\n");
amount=93, coins=[50, 25, 10, 5, 1]93 cents in coins:
49: report.append(amount / x + " x " + x + "c\n");amount=93, x=501 x 50c
510: amount %= x;amount=43, x=50—
69: report.append(amount / x + " x " + x + "c\n");amount=43, x=251 x 25c
710: amount %= x;amount=18, x=25—
89: report.append(amount / x + " x " + x + "c\n");amount=18, x=101 x 10c
910: amount %= x;amount=8, x=10—
109: report.append(amount / x + " x " + x + "c\n");amount=8, x=51 x 5c
1110: amount %= x;amount=3, x=5—
129: report.append(amount / x + " x " + x + "c\n");amount=3, x=13 x 1c
1310: amount %= x;amount=0, x=1—

The method is a greedy algorithm: at each step the largest coin that can be used is chosen. For 93 cents, first a 50 is used, leaving 43. Then a 25, leaving 18. A 10, leaving 8. A 5, leaving 3. Finally three 1s. Seven coins in all. Integer division gives the count and the remainder operator gives the remaining amount.

50cents× 125cents× 110cents× 15cents× 11cents× 3remaining amount: 0
Figure 9.27: Step 13. The loop has finished: 1 × 50, 1 × 25, 1 × 10, 1 × 5, and 3 × 1 cents.

For the coins 50, 25, 10, 5, 1, the greedy method always gives the fewest coins. This is not true for every coin system. For example, if the coins were 1, 3, and 4, then for 6 the greedy method would choose 4 + 1 + 1 (three coins), whereas 3 + 3 gives the same amount with two coins.

Example 9.14

The user typed 187 into the amount field. Which lines does the report contain?

187 / 50 = 3, remainder 37. 37 / 25 = 1, remainder 12. 12 / 10 = 1, remainder 2. 2 / 5 = 0, remainder 2. 2 / 1 = 2, remainder 0. In total 3 + 1 + 1 + 0 + 2 = 7 coins. The line with a count of zero is also written, because the loop adds a line for every coin value:

187 cents in coins:
3 x 50c
1 x 25c
1 x 10c
0 x 5c
2 x 1c

9.10.3main 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);
    });
}

main creates the window on the EDT, gives it a title, computes its size with pack(), and shows it. The really interesting part of the program is which events arrive depending on what the user types. Since a JFrame cannot be created in headless mode, the same fields, the listener, and the updateReport method were tried in a class without a window; insertions into and removals from the document were done directly. The events that arrived are these:

types 9                  insert
types 3                  insert
deletes everything       remove
abc                      insert
99999999999              remove insert
setText 287              remove insert
setText empty            remove
setText 287 (was empty)  insert
-7                       remove insert
68                       remove insert
187                      remove insert
with spaces              remove insert
Table 9.19: User actions, events, and the report (verified by running).
User / codeEventReport
Types 9insertUpdate9 cents: 0, 0, 0, 1 × 5, 4 × 1
Types 3 (field is 93)insertUpdate93 cents: 1, 1, 1, 1, 3
Deletes everythingremoveUpdateparseInt(""): “Not an integer or out of range”
abc or 99999999999NumberFormatExceptionThe same message
setText("287") (while the field has text)First removeUpdate, then insertUpdate5, 1, 1, 0, 2
setText("287") (while the field is empty)Only insertUpdate5, 1, 1, 0, 2
-7A valid number0, 0, 0, −1, −2: a check is missing

Every row of the table carries a lesson. While the user types “93,” two events arrive: one insertUpdate each for “9” and “3.” The report is updated on every key; the intermediate state (9 cents) is also visible for a moment. When the field is completely cleared, the text is the empty string and parseInt("") throws NumberFormatException. The first catch catches it.

99999999999 is a number, but it exceeds 2,147,483,647, the largest value of int. In this case too, parseInt throws NumberFormatException; that is why the message says “not an integer or out of range.” setText works not as a single operation but in two steps: it first removes the old text and then inserts the new one. If the field has text, two events arrive. At the first event the field is momentarily empty and the report shows the error message; the second event writes the correct report.

A negative number reveals a deficiency. -7 is a valid integer. In Java, integer division truncates toward zero and the remainder takes the sign of the dividend: -7 / 5 = -1, -7 % 5 = -2. The report contains meaningless lines such as -1 x 5c and -2 x 1c:

-7 cents in coins:
0 x 50c
0 x 25c
0 x 10c
-1 x 5c
-2 x 1c

The program should reject the negative value. A check right after parseInt is enough: if (amount < 0) { report.setText("Amount must be positive"); return; }.

The two catch blocks have different jobs. The first catches the expected error, that is, text that is not a number and values beyond the int limit. The second is a general safeguard for everything else. This block is necessary because getText(0, n) declares that it may throw BadLocationException, a checked exception. The compiler requires this exception to be handled; catch (Exception e) covers it too.

Example 9.15

What does the report show when 68 is typed into the change program?

68 / 50 = 1, remainder 18. 18 / 25 = 0, remainder 18. 18 / 10 = 1, remainder 8. 8 / 5 = 1, remainder 3. 3 / 1 = 3. The report begins with the line “68 cents in coins:” and continues with five lines:

68 cents in coins:
1 x 50c
0 x 25c
1 x 10c
1 x 5c
3 x 1c

9.11Best practices

A few habits determine the quality of GUI programs.

Use a layout manager
Do not give coordinates by hand. With a layout manager, the layout does not break at a different screen size, resolution, or font. Complex layouts are built with nested panels.
Choose meaningful names
Use names such as upperButton and amountField instead of b1 and t2. In an interface with dozens of components, the code stays readable only this way.
Think in terms of events
Design starts from the question “What should happen when the user does this?” A listener is written for each action; listeners do not rely on one another's order.
Separate the interface from the business logic
Rules such as the change calculation are kept in a separate method or class. That way they can be tested without the interface and used in another interface. Most of the outputs given in this chapter were obtained without opening a window, thanks to this separation.
Build the interface on the EDT
The body of main is a single call: SwingUtilities.invokeLater(() -> { … }).
Do not keep the EDT busy
If a listener does a long job (downloading a file, a large computation), the EDT cannot process any other event for that time and the window freezes. Such jobs are moved to a separate thread; the result is handed back to the EDT with invokeLater.
Example 9.16

How can the change calculation be separated from the interface?

The calculation is moved to a static method that takes an amount as input and returns the counts:

static int[] makeChange(int amount) {
    int[] coins = {50, 25, 10, 5, 1};
    int[] counts = new int[coins.length];
    for (int i = 0; i < coins.length; i++) {
        counts[i] = amount / coins[i];
        amount %= coins[i];
    }
    return counts;
}

updateReport now only reads the text, calls this method, and writes the result to the report. The method itself can be tried directly in a console program or a test: makeChange(93) returns [1, 1, 1, 1, 3].

9.12Solved problems

Example 9.17 (Problem 1)

If a button A and then a button B are added to the same NORTH region of a panel that uses BorderLayout, which one is visible in the north?

B. Each region holds a single component; the last one added wins. A remains in the panel (the component count is 2) but takes no part in the layout. In headless mode, on a 200 × 100 panel, B came out as (0, 0, 200, 26) and A as 0 × 0.

Example 9.18 (Problem 2)

If the user clicks the panel once and releases, which methods of MouseListener are called, and in what order?

mousePressed → mouseReleased → mouseClicked. If the pointer enters the panel from outside, mouseEntered arrives as well. If the mouse moves between the press and the release, mouseDragged events come in between and mouseClicked may not arrive.

Example 9.19 (Problem 3)

Which color does Color.RED.brighter() give?

Again (255, 0, 0). The red component is already at the maximum; 255 / 0.7 = 364 is capped at 255. The green and blue components are 0, and 0 / 0.7 = 0 stays.

Example 9.20 (Problem 4: a target)

A target made of five nested red and white rings, scaled to the size of the panel, is to be drawn. How is paintComponent written? Which calls are made on a 300 × 200 panel?

The center and the largest radius are computed as in the sign. In each round the loop reduces the radius by one fifth and alternates the colors:

int cx = getWidth() / 2, cy = getHeight() / 2;
int r = Math.min(cx, cy) - 5;
for (int i = 0; i < 5; i++) {
    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);
}

On 300 × 200, cx = 150, cy = 100, and r = 95. i * r / 5 is evaluated left to right: first the multiplication, then the integer division. The radii are 95, 76, 57, 38, and 19; the calls are fillOval(55, 5, 190, 190), (74, 24, 152, 152), (93, 43, 114, 114), (112, 62, 76, 76), and (131, 81, 38, 38). The circles are drawn from largest to smallest. If they were drawn from smallest to largest, the last, large circle would cover all the others.

Example 9.21 (Problem 5: undo with the right button)

In the drawing program, let a right click delete the last curve, and let dragging with the right button not draw anything. Which changes are needed?

A check is added at the beginning of mousePressed. If it is the right button, the last curve is removed and the method returns:

if (e.getButton() == MouseEvent.BUTTON3) {
    if (!curves.isEmpty()) curves.remove(curves.size() - 1);
    repaint();
    return;
}

At the beginning of mouseDragged, write if (!SwingUtilities.isLeftMouseButton(e)) return; as well. Without this line, dragging with the right button would add points to the previous curve in place of the one just deleted. When the list is empty, a right drag would throw IndexOutOfBoundsException: Index -1 out of bounds for length 0 through get(-1). The changes were tried by sending events in headless mode: after two curves were drawn, a right click reduced the number of curves to 1, and a right drag changed no points.

Example 9.22 (Problem 6: a temperature converter)

When °C is entered in a JTextField and a button is pressed, °F should be shown. How is the listener written?

convert.addActionListener(e -> {
    try {
        double c = Double.parseDouble(field.getText());
        result.setText(c * 9 / 5 + 32 + " °F");
    } catch (NumberFormatException ex) {
        result.setText("Not a number");
    }
});

When 100 is entered, 212.0 °F is shown; when −40 is entered, -40.0 °F is shown; −40 is the only temperature at which the two scales are equal. When abc is entered, parseDouble throws NumberFormatException and “Not a number” appears. In the expression c * 9 / 5 + 32 + " °F" the order matters: the numeric operations are done first, from left to right, and the string is appended last. The exception parameter inside the lambda is named ex instead of e, because e is already the lambda's parameter.

Two smaller exercises use the same patterns. In a counter window, the buttons “−1,” “+1,” and “Reset” change a private int count field and update the label. After two clicks on “+1” and one on “−1,” the label shows 1; after “Reset,” it shows 0. To add a “Clear” button to the drawing program, the button's listener runs curves.clear(); repaint();. The panel and the button go in the CENTER and SOUTH regions of the window.

9.13Common mistakes

In graphics programs, some mistakes come from the compiler, while others appear as the program silently misbehaving. The compiler messages were obtained with JDK 21.

Table 9.20: Common mistakes, their symptoms, and fixes.
MistakeSymptomFix
Forgetting the importcannot find symbol … class JFrameimport javax.swing.*;
No setVisible(true)The window never appearssetVisible(true) at the end of the setup
No EXIT_ON_CLOSEThe window closes, but the program keeps running in the backgroundsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
Misspelling the method name (paintcomponent)It is never called; with @Override: method does not override or implement a method from a supertypeThe correct name, and always @Override
Writing paintComponent without public/protectedattempting to assign weaker access privileges; was protectedprotected or public
Forgetting super.paintComponent(g)The background is not cleared, and remnants of old drawings stayThe first line of the body
Not writing all the methods of the interface… is not abstract and does not override abstract method mouseExited(MouseEvent) in MouseListenerDerive from MouseAdapter
Not registering the motion listenermouseDragged is never calledaddMouseMotionListener(…)
get(size()) for the last elementIndexOutOfBoundsException: Index 1 out of bounds for length 1get(size() - 1)
Modifying a local variable inside a lambdalocal variables referenced from a lambda expression must be final or effectively finalMake the variable a field
Passing a lambda for an interface with several methodsMouseListener is not a functional interfaceAn adapter or an anonymous class
Writing the constant without the class namecannot find symbol … variable CENTERBorderLayout.CENTER
List with java.awt.* and java.util.*reference to List is ambiguousimport java.util.List;
invokeAndWait from inside the EDTjava.lang.Error: Cannot call invokeAndWait from the event dispatcher threadCall directly on the EDT, or use invokeLater
A long job in a listenerThe window freezes and does not respond to clicksMove the job to a separate thread

When the import is forgotten, the compiler gives two errors for the same line: one for the type of the variable and one for the new expression.

Main.java:3: error: cannot find symbol
    JFrame f = new JFrame("x");
  symbol:   class JFrame
  location: class Main
Main.java:3: error: cannot find symbol
    JFrame f = new JFrame("x");
  symbol:   class JFrame
  location: class Main

The value of the @Override annotation is seen most clearly in a misspelled method name. Without the annotation, a class that writes paintcomponent (lowercase c) compiles without trouble. A new method has been defined, and Swing never calls it; the panel stays empty. When the annotation is added, the compiler finds the error immediately:

Main.java:7: error: method does not override or implement a method from a supertype
  @Override

paintComponent is defined as protected in JComponent. An overriding method cannot narrow the access: it can be protected or public. If no access modifier is written, the method gets package access and the compiler rejects it:

Main.java:7: error: paintComponent(Graphics) in Main cannot override paintComponent(Graphics) in JComponent
  void paintComponent(Graphics g) {
  attempting to assign weaker access privileges; was protected

Writing the constant without the class name gives a similar message:

Main.java:9: error: cannot find symbol
  p.add(new JButton("x"), CENTER);
  symbol:   variable CENTER
  location: class Main
Example 9.23

A drawing panel compiles, but the curves are not visible, remnants of old drawings stay, and an exception is thrown on the first drag. The code contains these lines: curves.get(curves.size()).add(e.getPoint()) and public void paintcomponent(Graphics g) { for (…) … }. What are the three mistakes?

The first is the name of the method: paintcomponent is a new method, and Swing does not call it. If @Override had been added, there would have been a compile error. Second, there is no super.paintComponent(g) inside the method; once the name is corrected, the background is not cleared and remnants stay. Third is the index of the last element: get(size()) throws IndexOutOfBoundsException; the correct form is size() - 1. That the code compiles does not show that it is free of errors; none of the three mistakes is caught by the compiler.

9.14Summary

  • A GUI program is event-driven: main only builds the interface, and the user's actions determine the flow. Most of the code consists of listeners.
  • The java.awt package contains Graphics, Color, Font, Point, the layout managers, and the event classes; the javax.swing package contains the components whose names start with J. Java itself draws the Swing components.
  • In screen coordinates, (0, 0) is the top-left corner of the component; x grows to the right and y downward.
  • For permanent drawing, derive from JPanel and override paintComponent(Graphics g). The first line of the body is super.paintComponent(g). Swing calls the method.
  • The draw… methods draw outlines and the fill… methods draw filled shapes. Ellipses and circles are given by their bounding rectangle: a circle with center (cx, cy) and radius r is fillOval(cx − r, cy − r, 2r, 2r). The y of drawString is the baseline.
  • A Graphics object remembers its color and font; setColor and setFont affect all later drawing. A shape drawn later covers an earlier one.
  • JFrame is a top-level window. The size is given with setSize or pack(), the close behavior is set with setDefaultCloseOperation(EXIT_ON_CLOSE), and setVisible(true) is called last. The default close behavior is HIDE_ON_CLOSE.
  • JPanel is both a container and a canvas; its default layout manager is FlowLayout. The content pane of a JFrame uses BorderLayout.
  • The fields x and y of Point are public int; getX() and getY() return double. translate moves relatively and setLocation moves absolutely.
  • Color is created from an RGB triple (0–255); it is immutable. darker() multiplies the components by 0.7 and brighter() divides them by 0.7; both truncate the result to integers and are not exact inverses of each other.
  • Font(name, style, size); the style constants are bit flags: BOLD | ITALIC = 3. deriveFont(float) changes the size and deriveFont(int) changes the style.
  • A layout manager computes the position and size of components by a rule. add only appends to the list; placement happens when the layout is computed.
  • FlowLayout arranges components row by row, centered, with a 5-pixel gap. BorderLayout places them in five regions: one component per region, the last one added wins, and the center takes the rest. GridLayout divides the container into equal cells. BoxLayout builds a single row or a single column.
  • A listener interface defines the methods for an event; a listener is registered with add…Listener. MouseListener reports press, release, click, enter, and exit; MouseMotionListener reports movement and dragging. Registration is by interface.
  • An adapter class (MouseAdapter) implements all the methods with empty bodies; a subclass writes only what it needs. An anonymous inner class suits a single-use listener.
  • A click produces pressed → released → clicked. MouseEvent gives the position relative to the component; getButton() tells the button (BUTTON3 is the right one).
  • Swing is single-threaded: components are built and modified only on the EDT. invokeLater puts a task in the queue and returns; invokeAndWait waits until the task finishes and throws an Error if called from inside the EDT. The queue is ordered.
  • A listener does not draw on the screen; it updates the data and requests repaint(). repaint() is a request; Swing calls paintComponent at a suitable moment.
  • ActionListener is a functional interface with a single method and can be written as a lambda. A local variable cannot be modified from inside a lambda; values that change become fields.
  • JLabel shows text, JTextField takes a single line and JTextArea multiple lines of text, and JScrollPane scrolls. getLineCount() is one more than the number of line breaks.
  • toUpperCase() depends on the locale; in Turkish, i → İ. To fix the result, give the locale explicitly.
  • In text components the model (Document) and the view are separate. A DocumentListener is called on every insertion and removal; setText produces two events on a non-empty field.
  • Best practices: use a layout manager, choose meaningful names, separate the business logic from the interface, build the interface on the EDT, and do not keep the EDT busy with long jobs.

9.15Key terms

  • graphical user interface (GUI)
  • component
  • container
  • layout manager
  • event
  • event listener
  • event dispatch thread (EDT)
  • thread
  • daemon thread
  • thread safety
  • anonymous class
  • inner class
  • lambda expression
  • functional interface
  • method overriding
  • implementing an interface
  • immutable
  • locale
  • event-driven programming
  • screen coordinates
  • bounding rectangle
  • canvas
  • content pane
  • adapter class
  • RGB color
  • clipping
  • Model-View-Controller (MVC)
  • Observer pattern
  • headless mode

9.16Test Yourself

  1. What is the bottom-right pixel painted by the calls g.drawRect(10, 20, 30, 40) and g.fillRect(10, 20, 30, 40)?

    Answer

    (40, 60) for drawRect and (39, 59) for fillRect. The outline also draws the right and bottom edge of the bounding rectangle and so is w + 1 pixels wide. The filled rectangle paints exactly w × h pixels. Both values were found by counting the painted pixels on an image.

  2. Which components does new Color(10, 20, 30).brighter() give?

    Answer

    (14, 28, 42). Each component is divided by 0.7 and truncated: 10 / 0.7 = 14.28 → 14; 20 / 0.7 = 28.57 → 28; 30 / 0.7 = 42.85 → 42. No component reaches 255, so the cap does not apply.

  3. A 300 × 200 pixel panel uses new BorderLayout(5, 5). Components preferring a height of 30 in the north and 20 in the south, a width of 60 in the west and 40 in the east, and one component in the center are added. What are the bounds of the center component?

    Answer

    (65, 35, 190, 140). The center starts to the right of the west region with a 5-pixel gap: x = 60 + 5. It starts below the north region with a 5-pixel gap: y = 30 + 5. The width is 300 − 60 − 40 − 2 × 5 = 190 and the height is 200 − 30 − 20 − 2 × 5 = 140. West and east have the same height and are at y = 35.

  4. The paintComponent method of the no-entry sign runs on a 300 × 300 pixel panel. What are r, r2, bw, and bh?

    Answer

    r = min(150, 150) − 5 = 145. r2 = (int) 130.5 = 130. bw = (int) (130 × 1.4) = 182. bh = (int) (130 × 0.35) = (int) 45.5 = 45. Truncation discards the half as well; with rounding the result would have been 46.

  5. What are the counts in the report when 41 is typed into the change program?

    Answer

    0 × 50, 1 × 25, 1 × 10, 1 × 5, 1 × 1. 41 / 50 = 0 (remainder 41), 41 / 25 = 1 (remainder 16), 16 / 10 = 1 (remainder 6), 6 / 5 = 1 (remainder 1), 1 / 1 = 1. Four coins in all.

  6. Does the following code compile?

    String name = " Ayşe ";
    name = name.trim();
    JButton b = new JButton("x");
    b.addActionListener(e -> System.out.println(name));
    Answer

    It does not compile: local variables referenced from a lambda expression must be final or effectively final. The lambda only reads name, but because name is reassigned on the second line, it is not effectively final. The fix is to put the trimmed value in a new variable: String clean = name.trim(); and use clean inside the lambda.

  7. A MouseAdapter object that overrides only mouseClicked is registered with a panel using addMouseMotionListener. Does the method run when the panel is clicked?

    Answer

    It does not. Because MouseAdapter implements three interfaces at once, the registration compiles, but the panel recognizes this object only as a motion listener. Click events go only to listeners registered with addMouseListener. When a click event was sent to the panel, the method was called 0 times.

  8. What does getLineCount() return for a JTextArea whose text is "a\n\nb\n"?

    Answer

    4. The text has three line breaks: “a,” an empty line, “b,” and an empty line after the last line break. The line count is one more than the number of line breaks.

9.17Further reading

  • Oracle, The Java Tutorials, “Creating a GUI With Swing”: the official, free account of components, layout managers, and event listeners. The lesson “Concurrency in Swing” explains the event dispatch thread in detail.
  • Oracle, The Java Tutorials, “Performing Custom Painting”: shows step by step, with an example, how paintComponent, repaint, and clipping work together.
  • C. S. Horstmann, Core Java, Volume I: Fundamentals (12th ed.), Chapters 10–11: covers graphics programming, event handling, and Swing components with an MVC perspective.
  • E. Gamma, R. Helm, R. Johnson, and J. Vlissides, Design Patterns: the original account of the Observer pattern; it explains why Swing listeners are designed the way they are.

9.18References

  1. Oracle, The Java Tutorials: Creating a GUI With Swing; Performing Custom Painting; Laying Out Components Within a Container; Writing Event Listeners; Concurrency in Swing.
  2. Oracle, Java SE 21 API Documentation: java.awt.Graphics, java.awt.Color, javax.swing.JFrame, javax.swing.SwingUtilities.
  3. P. Deitel and H. Deitel, Java: How to Program, 11th ed., Pearson (online chapters: Swing GUI Components; Graphics and Java 2D).
  4. K. Sierra, B. Bates, and T. Gee, Head First Java, 3rd ed., O'Reilly (Chapters 14–15: GUI, Swing, and events).
  5. C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson (Chapters 10–11: graphics programming, event handling, Swing).
  6. A. B. Downey and C. Mayfield, Think Java, 2nd ed., O'Reilly (Appendix C: Graphics).
  7. E. Gamma, R. Helm, R. Johnson, and J. Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994.

Related pages: Chapter 9 slides · Study questions · Swing Layout Managers simulator · Glossary · © Sercan Külcü. All rights reserved.