Chapter 9: Graphics and User Interfaces

Chapter 9: Graphics and User Interfaces · Study Questions
Event-driven programsGraphicsJFrame and JPanelPoint, Color, FontLayoutMouse eventsEDTText componentsMaking change
Sercan KÜLCÜ · Giresun University · Computer Engineering

Multiple Choice · Graphics Programming

Question 1: After main Ends

A Swing program's main method sets up the window, calls setVisible(true) and then ends. What happens next?

B: GUI programs are event-driven: main only builds the interface. Once the window is open, the event thread (EDT, a non-daemon thread) waits on the event queue and calls the matching listener for each event, such as a click. The JVM does not exit while this thread is running.

Classic Question · Graphics Programming

Question 2: Coordinates and the Bounding Rectangle

A panel makes the following drawings. (a) What is the center of the ellipse g.drawOval(30, 20, 80, 40), and at which y is its lowest pixel? (b) Write the fillOval call that draws the filled circle with center (120, 80) and radius 30. (c) For g.drawRect(20, 30, 50, 40), what point is the bottom-right corner pixel of the outline?

Show answer
  • (a) The ellipse fits in the rectangle with top-left corner (30, 20) and size 80 × 40: center (30 + 40, 20 + 20) = (70, 40). Since y grows downward, the lowest point is y = 20 + 40 = 60 (checked at pixel level).
  • (b) g.fillOval(120 - 30, 80 - 30, 60, 60), i.e. fillOval(90, 50, 60, 60): the parameters are the top-left corner and size of the bounding square, not the center.
  • (c) (70, 70): drawRect covers x..x+width and y..y+height (the outline is one pixel wider than width). Tested on a BufferedImage: (70, 70) is painted, (71, 70) is empty.

Step-by-Step Trace · No-Entry Sign

Question 3: The Sign on a 240 × 180 Panel

The no-entry sign is drawn by paintComponent, which runs on a 240 × 180 pixel panel (green background). What are the variables and the arguments of the three drawing calls?

The ground is painted with the background color (green).

Center: (240 / 2, 180 / 2) = (120, 90).

min(120, 90) − 5 = 85: chosen according to the shorter side.

85 × 0.9 = 76.5; (int) drops the fraction: 76.

76 × 1.4 = 106.4 → 106; 76 × 0.35 = 26.6 → 26 (truncation, not rounding).

fillOval(35, 5, 170, 170): white circle; the dashed square is the bounding rectangle.

fillOval(44, 14, 152, 152): the red circle is painted over the white one, leaving a 9-pixel ring.

bw / 2 = 53, bh / 2 = 13 → fillRect(67, 77, 106, 26). What is drawn later appears on top.

super.paintComponent(g);
Point c = new Point(getWidth() / 2,
    getHeight() / 2);
int r = Math.min(getWidth() / 2,
    getHeight() / 2) - 5;
int r2 = (int) (r * 0.9);
int bw = (int) (r2 * 1.4);
int bh = (int) (r2 * 0.35);
g.setColor(Color.WHITE);
g.fillOval(c.x - r, c.y - r, 2 * r, 2 * r);
g.setColor(Color.RED);
g.fillOval(c.x - r2, c.y - r2, r2 * 2, r2 * 2);
g.setColor(Color.WHITE);
g.fillRect(c.x - bw / 2, c.y - bh / 2, bw, bh);

Multiple Choice · Window and Panel

Question 4: The Close Button

JFrame is created, sized, and setVisible(true) is called; setDefaultCloseOperation is never called. What happens when the user clicks the × button of the window?

C: The default behavior is HIDE_ON_CLOSE: the window just becomes invisible; the JVM does not exit. To make the program exit, call setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE). Closing can be blocked altogether with DO_NOTHING_ON_CLOSE.

Multiple Choice · Window and Panel

Question 5: Two Buttons in the Content Pane

Two buttons are added to the window without specifying a region. What is visible when the window opens?

JFrame f = new JFrame("Test");
f.add(new JButton("One"));
f.add(new JButton("Two"));
f.setSize(300, 200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);

D: The content pane of a JFrame uses BorderLayout; a component added with add and no region goes into CENTER. Only one component fits in each region: the last one added wins. The One button stays in the container but its size becomes 0 × 0. Side-by-side placement is the behavior of FlowLayout (the default of JPanel). The same layout was tested on a 300 × 200 BorderLayout: Two (0, 0, 300, 200), One 0 × 0.

Output Question · Drawing Tools

Question 6: Point References and Color

Which three lines does the program print?

Point p = new Point(10, 20);
Point q = p;
q.translate(5, 5);
p.setLocation(p.x * 2, p.y);
System.out.println(p + " " + (q == p));
System.out.println(q.distance(30, 29));
Color k = new Color(200, 100, 50).darker();
System.out.println(k.getRed() + " " + k.getGreen()
    + " " + k.getBlue());
Show answer
java.awt.Point[x=30,y=25] true
4.0
140 70 35
  • Point q = p; does not create a new point: both variables refer to the same object. translate(5, 5) → (15, 25); setLocation(15 * 2, 25) → (30, 25). q == p is true.
  • Between (30, 25) and (30, 29) it is 4.0 (distance returns a double).
  • darker() multiplies each component by 0.7 and truncates to an integer: 140, 70, 35. The original color does not change; a new Color is returned.

Multiple Choice · Drawing Tools

Question 7: Bold and Italic

Font f = new Font("Serif", Font.BOLD | Font.ITALIC, 20); — what does f.getStyle() return?

A: Font.PLAIN = 0, Font.BOLD = 1, Font.ITALIC = 2 are bit flags; | (bitwise OR) combines the two: 1 | 2 = 3. isBold() and isItalic() both return true; the point size is a separate parameter (getSize() = 20).

Step-by-Step Trace · Layout Managers

Question 8: BorderLayout Regions

Components with given preferred sizes are added to a 300 × 200 panel (box(w, h) returns a JPanel preferring that size). After each addition, what are the components' positions and sizes?

Empty panel: 300 × 200, gap between regions 0.

north

North takes the full width; its height is the preferred height (30). The preferred width (100) is ignored.

northsouth

South goes to the bottom at full width: y = 200 − 20 = 180.

northsouthwest

West takes the height between north and south: 200 − 30 − 20 = 150; its width is the preferred 60.

northsouthwesteast

East goes to the right edge: x = 300 − 40 = 260.

northsouthwesteastcenter

No region given: CENTER. Its preferred size (10 × 10) is ignored; it takes all the remaining 200 × 150.

north 2southwesteastcenter

A second NORTH addition replaces the first: the new north is 40 high; west, east and center move down 10 and get shorter. The old north stays in the panel but is not laid out.

JPanel p = new JPanel(new BorderLayout());
p.setSize(300, 200);
p.add(box(100, 30), BorderLayout.NORTH);
p.add(box(100, 20), BorderLayout.SOUTH);
p.add(box(60, 50), BorderLayout.WEST);
p.add(box(40, 50), BorderLayout.EAST);
p.add(box(10, 10));
p.add(box(80, 40), BorderLayout.NORTH);

Multiple Choice · Layout Managers

Question 9: The Fifth Button in a GridLayout

new GridLayout(2, 3) is the layout of a 300 × 120 pixel panel to which 5 buttons are added in order. What are the position and size (x, y, width, height) of the 5th button?

B: GridLayout divides the panel into equal cells: 300 / 3 = 100 wide, 120 / 2 = 60 high. Buttons are placed row by row: 1–3 in the top row, 4 in the first cell and 5 in the second cell of the bottom row: x = 100, y = 60. The sixth cell stays empty; the cell size does not change with the number of components.

Multiple Choice · Mouse Events

Question 10: Drag Events Never Arrive

You want to draw by dragging on a panel, but mouseDragged never runs, while mousePressed does. Why?

MouseAdapter ma = new MouseAdapter() {
  public void mousePressed(MouseEvent e) {
    // start a new curve
  }
  public void mouseDragged(MouseEvent e) {
    // add a point to the last curve, repaint()
  }
};
panel.addMouseListener(ma);

C: MouseAdapter contains the methods of both MouseListener and MouseMotionListener with empty bodies, but registration is by interface: addMouseListener delivers only press, release, click, enter and exit events. Tested: with only addMouseListener, mouseDragged ran 0 times; after panel.addMouseMotionListener(ma), 1 time.

Output Question · Drawing Program

Question 11: Curves and the Number of drawLine Calls

In a drawing program (each press starts a new curve, each drag adds a point to the last curve; paintComponent uses, in each curve, prev as the first point and makes one drawLine call per point) the user presses at (10, 10), drags to (20, 10) and (30, 20), and releases; presses at (5, 5), drags to (6, 6) and releases. The window is then repainted. What are curves.size(), the number of points in each curve and the total number of drawLine calls?

Show answer
  • curves.size() = 2: each mousePressed adds a new inner list; mouseReleased does nothing because it is not written.
  • Curve 0: (10, 10), (20, 10), (30, 20) → 3 points. Curve 1: (5, 5), (6, 6) → 2 points.
  • drawLine = 3 + 2 = 5: since the inner loop starts at the first point, the first call joins the point to itself (a single pixel). The visible line segments are 2 + 1 = 3.

Because the data (the points) is stored, the same picture appears every time the window is repainted.

Multiple Choice · Mouse Events

Question 12: invokeLater and invokeAndWait

These lines run on the main thread. Which statement is certain about the order of the letters on screen?

SwingUtilities.invokeLater(
    () -> System.out.println("B"));
System.out.println("A");
SwingUtilities.invokeAndWait(
    () -> System.out.println("C"));
System.out.println("D");

D: invokeLater puts the job on the event queue and returns immediately; the scheduler decides whether B is printed before or after A. The event queue is ordered: B runs before C. invokeAndWait waits until C is finished, so D comes last. No window is needed; ABCD was seen in tests, but that is not a guarantee.

Multiple Choice · Text Components

Question 13: A Counter in a Lambda

To increase the counter on every click of the button, this code was written. What happens?

public static void main(String[] args) {
  int counter = 0;
  JButton b = new JButton("Click");
  b.addActionListener(e -> counter++);
}

A: The compiler message: local variables referenced from a lambda expression must be final or effectively final. A lambda captures the value of a local variable and cannot modify it. Fix: make counter a field of the class; a field can be modified from inside a lambda.

Output Question · Text Components

Question 14: JTextArea and JTextField

Which three lines does the program 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 ");
int n = Integer.parseInt(f.getText().trim());
System.out.println(n + 1);
Show answer
3
one line 1
43
  • The text became "x\ny\n": two line breaks, three lines (the last one empty). getLineCount() is the number of line breaks plus one.
  • setText erases the old content; append adds to the end: "one line", no line break → 1.
  • getText() always returns a String; without trim() removing the spaces, parseInt would throw NumberFormatException. 42 + 1 = 43.

Output Question · Case Converter

Question 15: Upper Case and Locale

Which four lines does the program print?

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);
Show answer
KIŞ İZMİR
kış izmir
KIŞ İZMIR
Kış İzmir
  • Turkish rules: i → İ, ı → I; İ → i, I → ı.
  • English rules: ı → I, i → I, İ stays unchanged: İZMIR. That is why the locale must be given explicitly in a text converter.
  • Strings are immutable: toUpperCase returns a new string; s is still "Kış İzmir". In a button listener the result is therefore written back with setText.

Step-by-Step Trace · Change Calculator

Question 16: updateReport: 187 Cents

The user typed 187 in the amount field. What lines does raporuGuncelle write to the report field?

The field says 187; the text is converted to an integer.

setText starts the report from scratch.

187 / 50 = 3 (integer division).

Remainder: 187 % 50 = 37.

37 / 25 = 1 (integer division).

Remainder: 37 % 25 = 12.

12 / 10 = 1 (integer division).

Remainder: 12 % 10 = 2.

2 / 5 = 0 (integer division).

Remainder: 2 % 5 = 2.

2 / 1 = 2 (integer division).

Remainder: 2 % 1 = 0. The loop ends: 3 + 1 + 1 + 0 + 2 = 7 coins.

void updateReport() {
  try {
    int 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());
  }
}

Coding Question · Graphics Programming

Question 17: A Target Board

JPanel subclass: write its paintComponent method so that it draws, in the middle of the panel, a target with 4 rings, scaled to the shorter side (10-pixel margin at the edge), alternating red and white from the outside in. On a 220 × 150 panel, which four fillOval calls are made?

Show answer
@Override
public void paintComponent(Graphics g) {
  super.paintComponent(g);
  int cx = getWidth() / 2, cy = getHeight() / 2;
  int r = Math.min(cx, cy) - 10;
  for (int i = 0; i < 4; i++) {
    int ri = r - i * r / 4;   // largest to smallest
    g.setColor(i % 2 == 0 ? Color.RED : Color.WHITE);
    g.fillOval(cx - ri, cy - ri, 2 * ri, 2 * ri);
  }
}

220 × 150: cx = 110, cy = 75, r = 65. i * r / 4 is evaluated left to right (multiplication first): ri = 65, 49, 33, 17 → fillOval(45, 10, 130, 130), (61, 26, 98, 98), (77, 42, 66, 66), (93, 58, 34, 34). The large circle must be drawn first; if drawn from small to large, the last big circle drawn would cover all the others.

Spot the Bug · Drawing Program

Question 18: Three Bugs

The panel compiles but the curves are not visible, leftovers of old drawings remain, and an exception is thrown on the first drag. Find the three bugs.

class Drawing extends JPanel {
  List<List<Point>> curves = new ArrayList<>();
  MouseAdapter m = new MouseAdapter() {
    public void mousePressed(MouseEvent e) { curves.add(new ArrayList<>()); }
    public void mouseDragged(MouseEvent e) {
      curves.get(curves.size()).add(e.getPoint()); repaint(); }
  };
  Drawing() { addMouseListener(m); addMouseMotionListener(m); }
  public void paintcomponent(Graphics g) {
    for (List<Point> eg : curves)
      for (int i = 1; i < eg.size(); i++)
        g.drawLine(eg.get(i - 1).x, eg.get(i - 1).y, eg.get(i).x, eg.get(i).y);
  }
}
Show answer
  1. paintcomponent (lowercase c) is a new method that Swing never calls; @Override would have caught this at compile time.
  2. super.paintComponent(g) is missing: the background is not cleared, so leftovers remain.
  3. The last element is at size() - 1; get(size()) throws IndexOutOfBoundsException.

The End

Chapter 9: Graphics and User Interfaces: Study Questions
Lecture slides: Chapter 9: Graphics and User Interfaces · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.