Exercise 9.1
1. Set window title to “Sample”:
JFrame frame = new JFrame("Sample");
OR
frame.setTitle("Sample");
2. Example 1:
javax.swing.JFrame frame = new javax.swing.JFrame("Graphical Greeting");
// ... class Drawing extends javax.swing.JComponent {
public void paint (java.awt.Graphics g) { /* ... */ }
}
3. g.drawString("Hello world",0,0);
in Example 1:
The string “Hello world” would be drawn with the baseline of the text at the top-left corner (0,0) of the drawing component. Most of the text would be clipped and invisible as there’s no space above y=0.
4. Changes in Example 4 for font style:
a. Italicized:
Font largeSerifFont = new Font("Serif", Font.ITALIC, 40);
b. Bold and italicized:
Font largeSerifFont = new Font("Serif", Font.BOLD | Font.ITALIC, 40);
5. Program to draw name and address:
import javax.swing.*; import java.awt.*;
public class NameAndAddress {
public static void main(String[] args) {
JFrame frame = new JFrame("Envelope - Jason Cameron & Justin Jiang");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 300);
frame.add(new JComponent() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
String[] lines = {"Jason Cameron & Justin Jiang", "123 Main Street", "Anytown, ST 12345"};
g.setFont(new Font("Serif", Font.PLAIN, 16));
FontMetrics fm = g.getFontMetrics();
int lineHeight = fm.getHeight();
int panelWidth = getWidth();
int panelHeight = getHeight();
int startY = (panelHeight - (lines.length * lineHeight)) / 2 + fm.getAscent();
for (int i = 0; i < lines.length; i++) {
int lineWidth = fm.stringWidth(lines[i]);
g.drawString(lines[i], (panelWidth - lineWidth) / 2, startY + (i * lineHeight));
}
}
});
frame.setLocationRelativeTo(null); frame.setVisible(true);
}
}
Exercise 9.2
1. Coordinates (region 300 wide, 200 high):
(a) upper left corner: (0, 0)
(b) midpoint of the bottom: (150, 200)
(c) centre of the left half: (75, 100)
(d) centre of the lower right quadrant: (225, 150)
2. Paint method for centered square (100px sides, in 400x200 window), colored lines:
// In a class extending JComponent protected void paintComponent(Graphics g) {
super.paintComponent(g);
int windowWidth = getWidth(); // Or 400 if fixed
int windowHeight = getHeight(); // Or 200 if fixed
int squareSize = 100; int x = (windowWidth - squareSize) / 2; int y = (windowHeight - squareSize) / 2; g.setColor(Color.GREEN);
g.drawLine(x, y, x + squareSize, y); // Top
g.drawLine(x, y + squareSize, x + squareSize, y + squareSize); // Bottom
g.setColor(Color.RED);
g.drawLine(x, y, x, y + squareSize); // Left
g.drawLine(x + squareSize, y, x + squareSize, y + squareSize); // Right
}
3. Paint method for nested diamond squares (smallest centered at (200,100), side 20px):
// In a class extending JComponent protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int centerX = 200, centerY = 100, smallestSide = 20, numSquares = 5, sideIncrement = 25; g2d.setColor(Color.BLACK);
for (int i = 0; i < numSquares; i++) {
int currentSide = smallestSide + i * sideIncrement; int halfSide = currentSide / 2; AffineTransform old = g2d.getTransform();
g2d.translate(centerX, centerY);
g2d.rotate(Math.toRadians(45));
g2d.drawRect(-halfSide, -halfSide, currentSide, currentSide);
g2d.setTransform(old);
}
g2d.dispose();
}
4. Mother’s Day Card Program:
import javax.swing.*; import java.awt.*; import java.awt.geom.AffineTransform;
public class MothersDayCard {
public static void main(String[] args) {
JFrame frame = new JFrame("Mother's Day - Jason & Justin");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 500);
frame.add(new CardPanel());
frame.setLocationRelativeTo(null); frame.setVisible(true);
}
}
class CardPanel extends JPanel {
public CardPanel() { setBackground(new Color(255, 230, 230)); }
protected void paintComponent(Graphics g) {
super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(new Color(220, 150, 150)); g2d.setStroke(new BasicStroke(3));
g2d.drawRoundRect(10, 10, getWidth() - 21, getHeight() - 21, 20, 20);
Font titleFont = new Font("Serif", Font.BOLD | Font.ITALIC, 30);
drawCenteredString(g2d, "Happy Mother's Day!", titleFont, new Color(180,0,90), 70);
drawFlower(g2d, getWidth()/2, 180);
Font msgFont = new Font("SansSerif", Font.PLAIN, 18);
drawCenteredString(g2d, "Thank you for everything!", msgFont, Color.DARK_GRAY, getHeight() - 120);
Font signFont = new Font("Brush Script MT", Font.PLAIN, 24);
drawCenteredString(g2d, "With Love, Jason & Justin", signFont, new Color(180,0,90), getHeight() - 70);
g2d.dispose();
}
void drawCenteredString(Graphics2D g2d, String text, Font font, Color color, int y) {
g2d.setFont(font); g2d.setColor(color);
FontMetrics fm = g2d.getFontMetrics();
g2d.drawString(text, (getWidth() - fm.stringWidth(text)) / 2, y);
}
void drawFlower(Graphics2D g2d, int cX, int cY) {
g2d.setColor(Color.YELLOW); g2d.fillOval(cX - 15, cY - 15, 30, 30);
g2d.setColor(new Color(255, 100, 150)); AffineTransform old = g2d.getTransform();
for (int i = 0; i < 8; i++) {
g2d.translate(cX, cY); g2d.rotate(Math.toRadians(45 * i));
g2d.fillOval(10, -10, 40, 20); g2d.setTransform(old);
}
}
}
Exercise 9.3 (Layout Managers)
1. GridLayout buttons display:
(14 buttons)
a. new GridLayout(3,5)
: 3 rows, 5 columns.
b. new GridLayout(5,4)
: 5 rows, 4 columns.
c. new GridLayout(4,0)
: 4 rows, 4 columns.
d. new GridLayout(0,6)
: 3 rows, 6 columns.
2. Program for 140x70 window, 3 buttons (“A”, “B”, “C”) side-by-side:
import javax.swing.*; import java.awt.*;
public class ThreeButtons {
public static void main(String[] args) {
JFrame frame = new JFrame("3 Buttons - Jason & Justin");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(140, 70);
frame.setLayout(new FlowLayout(FlowLayout.CENTER, 0, (70 - new JButton("A").getPreferredSize().height)/2 -5 ));
frame.add(new JButton("A")); frame.add(new JButton("B")); frame.add(new JButton("C"));
frame.setLocationRelativeTo(null); frame.setVisible(true);
}
}
3. Program for 200x200 window display (BorderLayout & FlowLayout):
import javax.swing.*; import java.awt.*;
public class BottomButtonsLayout {
public static void main(String[] args) {
JFrame frame = new JFrame("Bottom Buttons - Jason & Justin");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setLayout(new BorderLayout());
JLabel topLabel = new JLabel("top", SwingConstants.CENTER);
topLabel.setOpaque(true); topLabel.setBackground(Color.LIGHT_GRAY);
frame.add(topLabel, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
bottomPanel.add(new JButton("Yes"));
bottomPanel.add(new JButton("No"));
bottomPanel.add(new JButton("??"));
frame.add(bottomPanel, BorderLayout.SOUTH);
frame.setLocationRelativeTo(null); frame.setVisible(true);
}
}
4. Program for two solid red circles, resizing:
import javax.swing.*; import java.awt.*;
public class TwoRedCircles extends JComponent {
public TwoRedCircles() {
JFrame frame = new JFrame("Two Circles - Jason & Justin");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.add(this);
frame.setLocationRelativeTo(null); frame.setVisible(true);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g); Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.RED);
int w = getWidth(); int h = getHeight();
int diameter = Math.min(w, h) / 4; // Upper left quadrant center: (w/4, h/4) g2d.fillOval(w/4 - diameter/2, h/4 - diameter/2, diameter, diameter);
// Lower right quadrant center: (3w/4, 3h/4) g2d.fillOval(3*w/4 - diameter/2, 3*h/4 - diameter/2, diameter, diameter);
}
public static void main(String[] args) { new TwoRedCircles(); }
}
Exercise 9.4 (Button Events)
1. Program with “On” (white background) and “Off” (black background) buttons:
import javax.swing.*; import java.awt.*; import java.awt.event.*;
public class OnOffButtons implements ActionListener {
JFrame frame; JButton onButton, offButton; public OnOffButtons() {
frame = new JFrame("On/Off - Jason & Justin");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 100);
frame.setLayout(new FlowLayout());
onButton = new JButton("On"); onButton.addActionListener(this);
offButton = new JButton("Off"); offButton.addActionListener(this);
frame.add(onButton); frame.add(offButton);
frame.getContentPane().setBackground(Color.LIGHT_GRAY); // Initial
frame.setLocationRelativeTo(null); frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == onButton) frame.getContentPane().setBackground(Color.WHITE);
else if (e.getSource() == offButton) frame.getContentPane().setBackground(Color.BLACK);
}
public static void main(String[] args) { new OnOffButtons(); }
}
2. Modify Mother’s Day card to change image/text on button click:
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.AffineTransform;
public class InteractiveMothersDayCard implements ActionListener {
JFrame frame; CardPanelMovable panel; JButton changeButton; int messageState = 0; String[] messages = {"We love you, Mom!", "You're the best!", "Happy Mother's Day!"};
String[] authors = {"Jason & Justin", "Your loving children", "J & J"};
public InteractiveMothersDayCard() {
frame = new JFrame("Interactive Card - Jason & Justin");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 550);
frame.setLayout(new BorderLayout());
panel = new CardPanelMovable(messages[0], authors[0]);
frame.add(panel, BorderLayout.CENTER);
changeButton = new JButton("Next Message");
changeButton.addActionListener(this);
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(changeButton);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.setLocationRelativeTo(null); frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
messageState = (messageState + 1) % messages.length; panel.updateText(messages[messageState], authors[messageState]);
}
public static void main(String[] args) { new InteractiveMothersDayCard(); }
}
class CardPanelMovable extends JPanel {
private String mainMessage; private String authorMessage; public CardPanelMovable(String msg, String author) {
this.mainMessage = msg; this.authorMessage = author;
setBackground(new Color(255, 230, 230));
}
public void updateText(String msg, String author) {
this.mainMessage = msg; this.authorMessage = author; repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(new Color(220, 150, 150)); g2d.setStroke(new BasicStroke(3));
g2d.drawRoundRect(10, 10, getWidth() - 21, getHeight() - 21, 20, 20);
Font titleFont = new Font("Serif", Font.BOLD | Font.ITALIC, 30);
drawCenteredString(g2d, "Thinking of You!", titleFont, new Color(180,0,90), 70);
drawFlower(g2d, getWidth()/2, 180);
Font msgFont = new Font("SansSerif", Font.PLAIN, 18);
drawCenteredString(g2d, mainMessage, msgFont, Color.DARK_GRAY, getHeight() - 150);
Font signFont = new Font("Brush Script MT", Font.PLAIN, 24);
drawCenteredString(g2d, authorMessage, signFont, new Color(180,0,90), getHeight() - 100);
g2d.dispose();
}
void drawCenteredString(Graphics2D g2d, String text, Font font, Color color, int y) {
g2d.setFont(font); g2d.setColor(color); FontMetrics fm = g2d.getFontMetrics();
g2d.drawString(text, (getWidth() - fm.stringWidth(text)) / 2, y);
}
void drawFlower(Graphics2D g2d, int cX, int cY) { /* Same as 9.2.4 */ g2d.setColor(Color.YELLOW); g2d.fillOval(cX - 15, cY - 15, 30, 30);
g2d.setColor(new Color(255, 100, 150)); AffineTransform old = g2d.getTransform();
for (int i = 0; i < 8; i++) {
g2d.translate(cX, cY); g2d.rotate(Math.toRadians(45 * i));
g2d.fillOval(10, -10, 40, 20); g2d.setTransform(old);
}
}
}
3. Modify Example 3 (page 20-21) to add “Larger” and “Smaller” buttons for shape size:
import javax.swing.*; import java.awt.*; import java.awt.event.*;
public class ResizableShapes implements ActionListener {
JFrame frame; DrawingPanelShapes panel; JButton square, rectangle, circle, larger, smaller; int shapeType = 0; // 0: none, 1: square, 2: rect, 3: circle int shapeSize = 100; // Initial size dimension (e.g., side or diameter) final int SIZE_INCREMENT = 10;
public ResizableShapes() {
frame = new JFrame("Resizable Shapes - Jason & Justin");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
panel = new DrawingPanelShapes();
frame.add(panel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel(new FlowLayout());
square = new JButton("Square"); square.addActionListener(this); buttonPanel.add(square);
rectangle = new JButton("Rectangle"); rectangle.addActionListener(this); buttonPanel.add(rectangle);
circle = new JButton("Circle"); circle.addActionListener(this); buttonPanel.add(circle);
larger = new JButton("Larger"); larger.addActionListener(this); buttonPanel.add(larger);
smaller = new JButton("Smaller"); smaller.addActionListener(this); buttonPanel.add(smaller);
frame.add(buttonPanel, BorderLayout.NORTH);
frame.setLocationRelativeTo(null); frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if (src == square) shapeType = 1; else if (src == rectangle) shapeType = 2; else if (src == circle) shapeType = 3; else if (src == larger) shapeSize += SIZE_INCREMENT; else if (src == smaller) shapeSize = Math.max(SIZE_INCREMENT, shapeSize - SIZE_INCREMENT);
panel.updateShape(shapeType, shapeSize);
}
public static void main(String[] args) { new ResizableShapes(); }
}
class DrawingPanelShapes extends JComponent {
private int type = 0; private int size = 100; public void updateShape(int t, int s) { this.type = t; this.size = s; repaint(); }
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
int x = (getWidth() - size) / 2; int y = (getHeight() - size) / 2; int rectWidth = (int)(size * 1.5);
int rectHeight = size;
if (type == 1) g.fillRect(x, y, size, size);
else if (type == 2) g.fillRect((getWidth() - rectWidth)/2, (getHeight() - rectHeight)/2, rectWidth, rectHeight);
else if (type == 3) g.fillOval(x, y, size, size);
}
}
Exercise 9.5 (Mouse Events)
1. Difference between terms:
a. mousePressed
vs mouseClicked
:
mousePressed
: Event fires when a mouse button is pressed down.mouseClicked
: Event fires after a mouse button is pressed AND released without moving the mouse in between.
b.MouseListener
vsMouseMotionListener
:MouseListener
: Interface for discrete mouse events: press, release, click, enter, exit.MouseMotionListener
: Interface for continuous mouse events: move, drag.
c.MouseListener
vsMouseAdapter
:MouseListener
: An interface; any class implementing it MUST provide all five methods.MouseAdapter
: An abstract class that provides empty implementations forMouseListener
methods, used for convenience.
2. ActionListener
has no adapter. Oversight, laziness, or something else? Justify.
Something else. ActionListener
has only one method (actionPerformed
). Adapter classes are useful for interfaces with multiple methods to avoid implementing all of them. For a single-method interface, an adapter provides no benefit.
3. Program to draw a line between mouse press and release points (drag):
import javax.swing.*; import java.awt.*; import java.awt.event.*;
public class DragLine extends JComponent implements MouseListener, MouseMotionListener {
Point startPoint, endPoint; public DragLine() {
JFrame frame = new JFrame("Drag Line - Jason & Justin");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
this.addMouseListener(this); this.addMouseMotionListener(this);
frame.add(this);
frame.setLocationRelativeTo(null); frame.setVisible(true);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (startPoint != null && endPoint != null) {
g.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
}
}
public void mousePressed(MouseEvent e) { startPoint = e.getPoint(); endPoint = startPoint; repaint(); }
public void mouseDragged(MouseEvent e) { endPoint = e.getPoint(); repaint(); }
public void mouseReleased(MouseEvent e) { endPoint = e.getPoint(); repaint(); }
public void mouseClicked(MouseEvent e) {} public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {} public void mouseMoved(MouseEvent e) {}
public static void main(String[] args) { new DragLine(); }
}
4. Program to click two points, draw circle (first point center, second on circumference):
import javax.swing.*; import java.awt.*; import java.awt.event.*;
public class ClickCircle extends JComponent implements MouseListener {
Point centerPoint, radiusPoint; int clickCount = 0; public ClickCircle() {
JFrame frame = new JFrame("Click Circle - Jason & Justin");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
this.addMouseListener(this);
frame.add(this);
frame.setLocationRelativeTo(null); frame.setVisible(true);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g); Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if (centerPoint != null) {
g.setColor(Color.BLUE); g.fillOval(centerPoint.x - 3, centerPoint.y - 3, 6, 6);
}
if (centerPoint != null && radiusPoint != null) {
int radius = (int) Math.sqrt(Math.pow(radiusPoint.x - centerPoint.x, 2) + Math.pow(radiusPoint.y - centerPoint.y, 2));
g.setColor(Color.RED);
g.drawOval(centerPoint.x - radius, centerPoint.y - radius, 2 * radius, 2 * radius);
}
}
public void mouseClicked(MouseEvent e) {
clickCount++; if (clickCount == 1) { centerPoint = e.getPoint(); radiusPoint = null; }
else if (clickCount == 2) { radiusPoint = e.getPoint(); clickCount = 0; }
repaint();
}
public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {}
public static void main(String[] args) { new ClickCircle(); }
}
Exercise 9.6 (Text Input and Output)
1. Prevent user input in JTextField
called result
:
result.setEditable(false);
2. Changes to Example 7 (page 30-31) actionPerformed
for full name update on given/family name entry + <enter>
:
public void actionPerformed (ActionEvent e) {
String fullString = familyName.getText().trim() + ", " + givenName.getText().trim();
fullName.setText(fullString);
}
3. Program: input positive integer, press Enter, draw that number of random small circles:
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.Random;
public class DrawRandomCircles extends JComponent implements ActionListener {
JTextField inputField; int numCircles = 0; Random random = new Random();
public DrawRandomCircles() {
JFrame frame = new JFrame("Random Circles - Jason & Justin");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
inputField = new JTextField(10); inputField.addActionListener(this);
JPanel inputPanel = new JPanel(new FlowLayout());
inputPanel.add(new JLabel("Enter # circles:")); inputPanel.add(inputField);
frame.add(this, BorderLayout.CENTER);
frame.add(inputPanel, BorderLayout.SOUTH);
frame.setLocationRelativeTo(null); frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
numCircles = Integer.parseInt(inputField.getText().trim());
if (numCircles < 0) numCircles = 0; } catch (NumberFormatException ex) { numCircles = 0; }
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g); Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (int i = 0; i < numCircles; i++) {
int x = random.nextInt(getWidth() - 10);
int y = random.nextInt(getHeight() - 10 - 30);
g2d.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
g2d.fillOval(x, y, 10, 10);
}
}
public static void main(String[] args) { new DrawRandomCircles(); }
}
4. Simple Calculator Program (7x5 example shown):
import javax.swing.*; import java.awt.*; import java.awt.event.*;
public class SimpleCalculator implements ActionListener {
JTextField val1Field, val2Field, resultField; JButton addButton, subButton, mulButton, divButton; public SimpleCalculator() {
JFrame frame = new JFrame("A Simple Calculator - Jason & Justin");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel ioPanel = new JPanel(new GridLayout(3, 2, 5, 5));
val1Field = new JTextField(10);
val2Field = new JTextField(10);
resultField = new JTextField(10); resultField.setEditable(false);
ioPanel.add(new JLabel("First Value:")); ioPanel.add(val1Field);
ioPanel.add(new JLabel("Second Value:")); ioPanel.add(val2Field);
ioPanel.add(new JLabel("Result:")); ioPanel.add(resultField);
JPanel opPanel = new JPanel(new FlowLayout());
addButton = new JButton("+"); addButton.addActionListener(this); opPanel.add(addButton);
subButton = new JButton("-"); subButton.addActionListener(this); opPanel.add(subButton);
mulButton = new JButton("*"); mulButton.addActionListener(this); opPanel.add(mulButton);
divButton = new JButton("/"); divButton.addActionListener(this); opPanel.add(divButton);
frame.setLayout(new BorderLayout(5, 5));
frame.add(ioPanel, BorderLayout.NORTH);
frame.add(opPanel, BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null); frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
double val1 = Double.parseDouble(val1Field.getText().trim());
double val2 = Double.parseDouble(val2Field.getText().trim());
double result = 0; Object src = e.getSource();
if (src == addButton) result = val1 + val2; else if (src == subButton) result = val1 - val2; else if (src == mulButton) result = val1 * val2; else if (src == divButton) {
if (val2 == 0) { resultField.setText("Error: Div by 0"); return; }
result = val1 / val2; }
resultField.setText(String.format("%.2f", result));
} catch (NumberFormatException ex) {
resultField.setText("Error: Invalid input");
}
}
public static void main(String[] args) { new SimpleCalculator(); }
}
9.8 Review Exercises
1. Error in each statement (g is Graphics object):
a. g.setColor(Color.Red);
Error: Color.Red
should be Color.RED
.
b. g.setFont("Serif");
Error: setFont
method expects a Font
object, not a String.