- •CONTENTS
- •1.1 Introduction
- •1.2 What Is a Computer?
- •1.3 Programs
- •1.4 Operating Systems
- •1.5 Java, World Wide Web, and Beyond
- •1.6 The Java Language Specification, API, JDK, and IDE
- •1.7 A Simple Java Program
- •1.8 Creating, Compiling, and Executing a Java Program
- •1.9 (GUI) Displaying Text in a Message Dialog Box
- •2.1 Introduction
- •2.2 Writing Simple Programs
- •2.3 Reading Input from the Console
- •2.4 Identifiers
- •2.5 Variables
- •2.7 Named Constants
- •2.8 Numeric Data Types and Operations
- •2.9 Problem: Displaying the Current Time
- •2.10 Shorthand Operators
- •2.11 Numeric Type Conversions
- •2.12 Problem: Computing Loan Payments
- •2.13 Character Data Type and Operations
- •2.14 Problem: Counting Monetary Units
- •2.15 The String Type
- •2.16 Programming Style and Documentation
- •2.17 Programming Errors
- •2.18 (GUI) Getting Input from Input Dialogs
- •3.1 Introduction
- •3.2 boolean Data Type
- •3.3 Problem: A Simple Math Learning Tool
- •3.4 if Statements
- •3.5 Problem: Guessing Birthdays
- •3.6 Two-Way if Statements
- •3.7 Nested if Statements
- •3.8 Common Errors in Selection Statements
- •3.9 Problem: An Improved Math Learning Tool
- •3.10 Problem: Computing Body Mass Index
- •3.11 Problem: Computing Taxes
- •3.12 Logical Operators
- •3.13 Problem: Determining Leap Year
- •3.14 Problem: Lottery
- •3.15 switch Statements
- •3.16 Conditional Expressions
- •3.17 Formatting Console Output
- •3.18 Operator Precedence and Associativity
- •3.19 (GUI) Confirmation Dialogs
- •4.1 Introduction
- •4.2 The while Loop
- •4.3 The do-while Loop
- •4.4 The for Loop
- •4.5 Which Loop to Use?
- •4.6 Nested Loops
- •4.7 Minimizing Numeric Errors
- •4.8 Case Studies
- •4.9 Keywords break and continue
- •4.10 (GUI) Controlling a Loop with a Confirmation Dialog
- •5.1 Introduction
- •5.2 Defining a Method
- •5.3 Calling a Method
- •5.4 void Method Example
- •5.5 Passing Parameters by Values
- •5.6 Modularizing Code
- •5.7 Problem: Converting Decimals to Hexadecimals
- •5.8 Overloading Methods
- •5.9 The Scope of Variables
- •5.10 The Math Class
- •5.11 Case Study: Generating Random Characters
- •5.12 Method Abstraction and Stepwise Refinement
- •6.1 Introduction
- •6.2 Array Basics
- •6.3 Problem: Lotto Numbers
- •6.4 Problem: Deck of Cards
- •6.5 Copying Arrays
- •6.6 Passing Arrays to Methods
- •6.7 Returning an Array from a Method
- •6.8 Variable-Length Argument Lists
- •6.9 Searching Arrays
- •6.10 Sorting Arrays
- •6.11 The Arrays Class
- •7.1 Introduction
- •7.2 Two-Dimensional Array Basics
- •7.3 Processing Two-Dimensional Arrays
- •7.4 Passing Two-Dimensional Arrays to Methods
- •7.5 Problem: Grading a Multiple-Choice Test
- •7.6 Problem: Finding a Closest Pair
- •7.7 Problem: Sudoku
- •7.8 Multidimensional Arrays
- •8.1 Introduction
- •8.2 Defining Classes for Objects
- •8.3 Example: Defining Classes and Creating Objects
- •8.4 Constructing Objects Using Constructors
- •8.5 Accessing Objects via Reference Variables
- •8.6 Using Classes from the Java Library
- •8.7 Static Variables, Constants, and Methods
- •8.8 Visibility Modifiers
- •8.9 Data Field Encapsulation
- •8.10 Passing Objects to Methods
- •8.11 Array of Objects
- •9.1 Introduction
- •9.2 The String Class
- •9.3 The Character Class
- •9.4 The StringBuilder/StringBuffer Class
- •9.5 Command-Line Arguments
- •9.6 The File Class
- •9.7 File Input and Output
- •9.8 (GUI) File Dialogs
- •10.1 Introduction
- •10.2 Immutable Objects and Classes
- •10.3 The Scope of Variables
- •10.4 The this Reference
- •10.5 Class Abstraction and Encapsulation
- •10.6 Object-Oriented Thinking
- •10.7 Object Composition
- •10.8 Designing the Course Class
- •10.9 Designing a Class for Stacks
- •10.10 Designing the GuessDate Class
- •10.11 Class Design Guidelines
- •11.1 Introduction
- •11.2 Superclasses and Subclasses
- •11.3 Using the super Keyword
- •11.4 Overriding Methods
- •11.5 Overriding vs. Overloading
- •11.6 The Object Class and Its toString() Method
- •11.7 Polymorphism
- •11.8 Dynamic Binding
- •11.9 Casting Objects and the instanceof Operator
- •11.11 The ArrayList Class
- •11.12 A Custom Stack Class
- •11.13 The protected Data and Methods
- •11.14 Preventing Extending and Overriding
- •12.1 Introduction
- •12.2 Swing vs. AWT
- •12.3 The Java GUI API
- •12.4 Frames
- •12.5 Layout Managers
- •12.6 Using Panels as Subcontainers
- •12.7 The Color Class
- •12.8 The Font Class
- •12.9 Common Features of Swing GUI Components
- •12.10 Image Icons
- •13.1 Introduction
- •13.2 Exception-Handling Overview
- •13.3 Exception-Handling Advantages
- •13.4 Exception Types
- •13.5 More on Exception Handling
- •13.6 The finally Clause
- •13.7 When to Use Exceptions
- •13.8 Rethrowing Exceptions
- •13.9 Chained Exceptions
- •13.10 Creating Custom Exception Classes
- •14.1 Introduction
- •14.2 Abstract Classes
- •14.3 Example: Calendar and GregorianCalendar
- •14.4 Interfaces
- •14.5 Example: The Comparable Interface
- •14.6 Example: The ActionListener Interface
- •14.7 Example: The Cloneable Interface
- •14.8 Interfaces vs. Abstract Classes
- •14.9 Processing Primitive Data Type Values as Objects
- •14.10 Sorting an Array of Objects
- •14.11 Automatic Conversion between Primitive Types and Wrapper Class Types
- •14.12 The BigInteger and BigDecimal Classes
- •14.13 Case Study: The Rational Class
- •15.1 Introduction
- •15.2 Graphical Coordinate Systems
- •15.3 The Graphics Class
- •15.4 Drawing Strings, Lines, Rectangles, and Ovals
- •15.5 Case Study: The FigurePanel Class
- •15.6 Drawing Arcs
- •15.7 Drawing Polygons and Polylines
- •15.8 Centering a String Using the FontMetrics Class
- •15.9 Case Study: The MessagePanel Class
- •15.10 Case Study: The StillClock Class
- •15.11 Displaying Images
- •15.12 Case Study: The ImageViewer Class
- •16.1 Introduction
- •16.2 Event and Event Source
- •16.3 Listeners, Registrations, and Handling Events
- •16.4 Inner Classes
- •16.5 Anonymous Class Listeners
- •16.6 Alternative Ways of Defining Listener Classes
- •16.7 Problem: Loan Calculator
- •16.8 Window Events
- •16.9 Listener Interface Adapters
- •16.10 Mouse Events
- •16.11 Key Events
- •16.12 Animation Using the Timer Class
- •17.1 Introduction
- •17.2 Buttons
- •17.3 Check Boxes
- •17.4 Radio Buttons
- •17.5 Labels
- •17.6 Text Fields
- •17.7 Text Areas
- •17.8 Combo Boxes
- •17.9 Lists
- •17.10 Scroll Bars
- •17.11 Sliders
- •17.12 Creating Multiple Windows
- •18.1 Introduction
- •18.2 Developing Applets
- •18.3 The HTML File and the <applet> Tag
- •18.4 Applet Security Restrictions
- •18.5 Enabling Applets to Run as Applications
- •18.6 Applet Life-Cycle Methods
- •18.7 Passing Strings to Applets
- •18.8 Case Study: Bouncing Ball
- •18.9 Case Study: TicTacToe
- •18.10 Locating Resources Using the URL Class
- •18.11 Playing Audio in Any Java Program
- •18.12 Case Study: Multimedia Animations
- •19.1 Introduction
- •19.2 How is I/O Handled in Java?
- •19.3 Text I/O vs. Binary I/O
- •19.4 Binary I/O Classes
- •19.5 Problem: Copying Files
- •19.6 Object I/O
- •19.7 Random-Access Files
- •20.1 Introduction
- •20.2 Problem: Computing Factorials
- •20.3 Problem: Computing Fibonacci Numbers
- •20.4 Problem Solving Using Recursion
- •20.5 Recursive Helper Methods
- •20.6 Problem: Finding the Directory Size
- •20.7 Problem: Towers of Hanoi
- •20.8 Problem: Fractals
- •20.9 Problem: Eight Queens
- •20.10 Recursion vs. Iteration
- •20.11 Tail Recursion
- •APPENDIXES
- •INDEX
520 Chapter 15 |
Graphics |
|
|
76 |
int xSecond = (int)(xCenter + sLength * |
|
77 |
Math.sin(second * (2 * Math.PI / 60))); |
|
78 |
int ySecond = (int)(yCenter - sLength * |
|
79 |
Math.cos(second * (2 * Math.PI / 60))); |
|
80 |
g.setColor(Color.red); |
|
81 |
g.drawLine(xCenter, yCenter, xSecond, ySecond); |
|
82 |
|
|
83 |
// Draw minute hand |
|
84 |
int mLength = (int)(clockRadius * 0.65); |
|
85 |
int xMinute = (int)(xCenter + mLength * |
|
86 |
Math.sin(minute * (2 * Math.PI / 60))); |
|
87 |
int yMinute = (int)(yCenter - mLength * |
|
88 |
Math.cos(minute * (2 * Math.PI / 60))); |
|
89 |
g.setColor(Color.blue); |
|
90 |
g.drawLine(xCenter, yCenter, xMinute, yMinute); |
|
91 |
|
|
92 |
// Draw hour hand |
|
93 |
int hLength = (int)(clockRadius * 0.5); |
|
94 |
int xHour = (int)(xCenter + hLength * |
|
95 |
Math.sin((hour % 12 + minute / 60.0) * (2 * Math.PI / 12))); |
|
96 |
int yHour = (int)(yCenter - hLength * |
|
97 |
Math.cos((hour % 12 + minute / 60.0) * (2 * Math.PI / 12))); |
|
98 |
g.setColor(Color.green); |
|
99 |
g.drawLine(xCenter, yCenter, xHour, yHour); |
|
100 |
} |
|
101 |
|
|
102 |
public void setCurrentTime() { |
|
103 |
// Construct a calendar for the current date and time |
get current time |
104 |
Calendar calendar = new GregorianCalendar(); |
|
105 |
|
|
106 |
// Set current hour, minute and second |
|
107 |
this.hour = calendar.get(Calendar.HOUR_OF_DAY); |
|
108 |
this.minute = calendar.get(Calendar.MINUTE); |
|
109 |
this.second = calendar.get(Calendar.SECOND); |
|
110 |
} |
|
111 |
|
override |
112 |
public Dimension getPreferredSize() { |
getPreferredSize |
113 |
return new Dimension(200, 200); |
|
114 |
} |
|
115 |
} |
|
The program enables the clock size to adjust as the frame resizes. Every time you resize the |
|
|
frame, the paintComponent method is automatically invoked to paint the new frame. The |
|
|
paintComponent method displays the clock in proportion to the panel width (getWidth()) |
|
|
and height (getHeight()) (lines 60–63 in StillClock). |
15.11 Displaying Images
You learned how to create image icons and display them in labels and buttons in §12.10, “Image Icons.” For example, the following statements create an image icon and display it in a label:
ImageIcon icon = new ImageIcon("image/us.gif");
JLabel jlblImage = new JLabel(imageIcon);
An image icon displays a fixed-size image. To display an image in a flexible size, you need to use the java.awt.Image class. An image can be created from an image icon using the getImage() method as follows:
Image image = imageIcon.getImage();
15.11 Displaying Images 521
Using a label as an area for displaying images is simple and convenient, but you don’t have much control over how the image is displayed. A more flexible way to display images is to use the drawImage method of the Graphics class on a panel. Four versions of the drawImage method are shown in Figure 15.23.
java.awt.Graphics
+drawImage(image: Image, x: int, y: int, bgcolor: Color, observer: ImageObserver): void
+drawImage(image: Image, x: int, y: int, observer: ImageObserver): void
+drawImage(image: Image, x: int, y: int, width: int, height: int, observer: ImageObserver): void
+drawImage(image: Image, x: int, y: int, width: int, height: int, bgcolor: Color, observer: ImageObserver): void
Draws the image in a specified location. The image's top-left corner is at (x, y) in the graphics context's coordinate space. Transparent pixels in the image are drawn in the specified color bgcolor. The observer is the object on which the image is displayed. The image is cut off if it is
larger than the area it is being drawn on.
Same as the preceding method except that it does not specify a background color.
Draws a scaled version of the image that can fill all of the available space in the specified rectangle.
Same as the preceding method except that it provides a solid background color behind the image being drawn.
FIGURE 15.23 You can apply the drawImage method on a Graphics object to display an image in a GUI component.
ImageObserver specifies a GUI component for receiving notifications of image information as the image is constructed. To draw images using the drawImage method in a Swing component, such as JPanel, override the paintComponent method to tell the component how to display the image in the panel.
Listing 15.11 gives the code that displays an image from image/us.gif. The file image/us.gif (line 20) is under the class directory. An Image object is obtained in line 21. The drawImage method displays the image to fill in the whole panel, as shown in Figure 15.24.
FIGURE 15.24 An image is displayed in a panel.
LISTING 15.11 DisplayImage.java
1 import java.awt.*;
2 import javax.swing.*;
3
4 public class DisplayImage extends JFrame {
5public DisplayImage() {
6 |
add(new ImagePanel()); |
add panel |
7 |
} |
|
8 |
|
|
9 |
public static void main(String[] args) { |
|
10JFrame frame = new DisplayImage();
11frame.setTitle("DisplayImage");
12frame.setSize(300, 300);
13frame.setLocationRelativeTo(null); // Center the frame
14frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
522 Chapter 15 Graphics
|
15 |
|
frame.setVisible(true); |
||||
|
16 |
} |
|
|
|
|
|
|
17 |
} |
|
|
|
|
|
|
18 |
|
|
|
|
|
|
panel class |
19 |
class ImagePanel extends JPanel { |
|
||||
create image icon |
20 |
private |
ImageIcon imageIcon = new ImageIcon("image/us.gif"); |
||||
get image |
21 |
private |
Image image = imageIcon.getImage(); |
|
|||
|
22 |
|
|
|
|
|
|
|
23 |
/** Draw image on the panel */ |
|||||
override paintComponent |
24 |
|
protected void paintComponent(Graphics g) { |
|
|||
|
25 |
|
super.paintComponent(g); |
||||
|
26 |
|
|
|
|
|
|
|
27 |
|
if (image != null) |
||||
draw image |
28 |
|
|
g.drawImage(image, 0, 0, getWidth(), getHeight(), this); |
|||
|
29 |
} |
|
|
|
|
|
|
30 |
} |
|
|
|
|
|
|
15.12 Case Study: The ImageViewer Class |
|
Displaying an image is a common task in Java programming. This case study develops a |
|
reusable component named ImageViewer that displays an image on a panel. The class con- |
|
tains the properties image, stretched, xCoordinate, and yCoordinate, with associated |
|
accessor and mutator methods, as shown in Figure 15.25. |
stretchable image |
You can use images in Swing components such as JLabel and JButton, but these images |
|
are not stretchable. The image in an ImageViewer can be stretched. |
|
Let us write a test program in Listing 15.12 that displays six images using the |
|
ImageViewer class. Figure 15.26 shows a sample run of the program. |
javax.swing.JPanel
ImageViewer
-image: Image -stretched: boolean -xCoordinate: int -yCoordinate: int
+ImageViewer() +ImageViewer(image: Image)
The get and set methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.
Image in the image viewer.
True if the image is stretched in the viewer.
x-coordinate of the upper-left corner of the image in the viewer.
y-coordinate of the upper-left corner of the image in the viewer.
Constructs an image viewer with no image.
Constructs an image viewer with the specified image.
FIGURE 15.25 The ImageViewer class displays an image on a panel.
FIGURE 15.26 Six images are displayed in six ImageViewer components.
15.12 Case Study: The ImageViewer Class 523
LISTING 15.12 SixFlags.java
1 import javax.swing.*;
2 import java.awt.*;
3
4 public class SixFlags extends JFrame {
5public SixFlags() {
6 |
Image image1 = new ImageIcon("image/us.gif").getImage(); |
create image |
7Image image2 = new ImageIcon("image/ca.gif").getImage();
8 Image image3 = new ImageIcon("image/india.gif").getImage();
9 Image image4 = new ImageIcon("image/uk.gif").getImage();
10Image image5 = new ImageIcon("image/china.gif").getImage();
11Image image6 = new ImageIcon("image/norway.gif").getImage();
13setLayout(new GridLayout(2, 0, 5, 5));
14 |
add(new ImageViewer(image1)); |
create image viewer |
15add(new ImageViewer(image2));
16add(new ImageViewer(image3));
17add(new ImageViewer(image4));
18add(new ImageViewer(image5));
19add(new ImageViewer(image6));
20}
21 |
|
22 |
public static void main(String[] args) { |
23 |
SixFlags frame = new SixFlags(); |
24 |
frame.setTitle("SixFlags"); |
25 |
frame.setSize(400, 320); |
26 |
frame.setLocationRelativeTo(null); // Center the frame |
27 |
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); |
28 |
frame.setVisible(true); |
29 |
} |
30 |
} |
The ImageViewer class is implemented in Listing 15.13. (Note: You may skip the |
implementation |
implementation.) The accessor and mutator methods for the properties image, stretched, |
skip implementation? |
xCoordinate, and yCoordinate are easy to implement. The paintComponent method |
|
(lines 26–35) displays the image on the panel. Line 29 ensures that the image is not null |
|
before displaying it. Line 30 checks whether the image is stretched or not. |
|
LISTING 15.13 ImageViewer.java
1 import java.awt.*;
2 import javax.swing.*;
3
4 public class ImageViewer extends JPanel {
5/** Hold value of property image. */
6 |
private |
java.awt.Image image; |
properties |
7 |
|
|
|
8 |
/** Hold value of property stretched. */ |
|
|
9 |
private |
boolean stretched = true; |
|
10
11/** Hold value of property xCoordinate. */
12private int xCoordinate;
13
14/** Hold value of property yCoordinate. */
15private int yCoordinate;
16
524 Chapter 15 |
Graphics |
|
|
|
|
|
|
|
17 |
/** Construct an empty image viewer */ |
|||||
constructor |
18 |
public ImageViewer() { |
|||||
|
19 |
} |
|
|
|
|
|
|
20 |
|
|
|
|
|
|
|
21 |
/** Construct an image viewer for a specified Image object */ |
|||||
constructor |
22 |
public ImageViewer(Image image) { |
|||||
|
23 |
|
this.image = image; |
||||
|
24 |
} |
|
|
|
|
|
|
25 |
|
|
|
|
|
|
|
26 |
protected void paintComponent(Graphics g) |
{ |
||||
|
27 |
|
super.paintComponent(g); |
||||
|
28 |
|
|
|
|
|
|
image null? |
29 |
|
if (image != null) |
|
|
||
|
30 |
|
if |
(isStretched() |
) |
|
|
stretched |
31 |
|
g.drawImage(image, xCoordinate, yCoordinate, |
||||
|
32 |
|
|
getWidth(), getHeight(), this); |
|||
|
33 |
|
else |
||||
nonstretched |
34 |
|
g.drawImage(image, xCoordinate, yCoordinate, this); |
||||
|
35 |
} |
|
|
|
|
|
|
36 |
|
|
|
|
|
|
|
37 |
/** Return value of property image */ |
|||||
|
38 |
public java.awt.Image getImage() { |
|||||
|
39 |
|
return image; |
||||
|
40 |
} |
|
|
|
|
|
|
41 |
|
|
|
|
|
|
|
42 |
/** Set a new value for property image */ |
|||||
|
43 |
public void setImage(java.awt.Image image) { |
|||||
|
44 |
this.image = image; |
|||||
|
45 |
repaint(); |
|||||
|
46 |
} |
|
|
|
|
|
|
47 |
|
|
|
|
|
|
|
48 |
/** Return value of property stretched */ |
|||||
|
49 |
public boolean isStretched() { |
|||||
|
50 |
return stretched; |
|||||
|
51 |
} |
|
|
|
|
|
|
52 |
|
|
|
|
|
|
|
53 |
/** Set a new value for property stretched */ |
|||||
|
54 |
public void setStretched(boolean stretched) { |
|||||
|
55 |
this.stretched = stretched; |
|||||
|
56 |
repaint(); |
|||||
|
57 |
} |
|
|
|
|
|
|
58 |
|
|
|
|
|
|
|
59 |
/** Return value of property xCoordinate */ |
|||||
|
60 |
public int getXCoordinate() { |
|||||
|
61 |
return xCoordinate; |
|||||
|
62 |
} |
|
|
|
|
|
|
63 |
|
|
|
|
|
|
|
64 |
/** Set a new value for property xCoordinate */ |
|||||
|
65 |
public void setXCoordinate(int xCoordinate) { |
|||||
|
66 |
this.xCoordinate = xCoordinate; |
|||||
|
67 |
repaint(); |
|||||
|
68 |
} |
|
|
|
|
|
|
69 |
|
|
|
|
|
|
|
70 |
/** Return value of property yCoordinate */ |
|||||
|
71 |
public int getYCoordinate() { |
|||||
|
72 |
return yCoordinate; |
|||||
|
73 |
} |
|
|
|
|
|
|
74 |
|
|
|
|
|
|
|
75 |
/** Set a new value for property yCoordinate */ |
Review Questions 525
76public void setYCoordinate(int yCoordinate) {
77this.yCoordinate = yCoordinate;
78repaint();
79}
80}
CHAPTER SUMMARY
1.Each component has its own coordinate system with the origin (0, 0) at the upper-left corner of the window. The x-coordinate increases to the right, and the y-coordinate increases downward.
2.The Graphics class is an abstract class for displaying figures and images on the screen on different platforms. The Graphics class is implemented on the native platform in the JVM. When you use the paintComponent(g) method to paint on a GUI component, this g is an instance of a concrete subclass of the abstract Graphics class for the specific platform. The Graphics class encapsulates the platform details and enables you to draw things uniformly without concern for the specific platform.
3.Invoking super.paintComponent(g) is necessary to ensure that the viewing area is cleared before a new drawing is displayed. The user can request the component to be redisplayed by invoking the repaint() method defined in the Component class. Invoking repaint() causes paintComponent to be invoked by the JVM. The user should never invoke paintComponent directly. For this reason, the protected visibility is sufficient for paintComponent.
4.Normally you use JPanel as a canvas. To draw on a JPanel, you create a new class that extends JPanel and overrides the paintComponent method to tell the panel how to draw things.
5.You can set fonts for the components or subjects you draw, and use font metrics to measure font size. Fonts and font metrics are encapsulated in the classes Font and FontMetrics. FontMetrics can be used to compute the exact length and width of a string, which is helpful for measuring the size of a string in order to display it in the right position.
6.The Component class has the setBackground, setForeground, and setFont methods. These methods are used to set colors and fonts for the entire component. Suppose you want to draw several messages in a panel with different colors and fonts; you have to use the setColor and setFont methods in the Graphics class to set the color and font for the current drawing.
7.To display an image, first create an image icon. You can then use ImageIcon’s getImage() method to get an Image object for the image and draw the image using the drawImage method in the java.awt.Graphics class.
REVIEW QUESTIONS
Sections 15.2–15.3
15.1Suppose that you want to draw a new message below an existing message. Should the x-coordinate, y-coordinate, or both increase or decrease?
15.2Why is the Graphics class abstract? How is a Graphics object created?
15.3Describe the paintComponent method. Where is it defined? How is it invoked? Can it be directly invoked? How can a program cause this method to be invoked?
526 Chapter 15 Graphics
15.4Why is the paintComponent method protected? What happens if you change it to public or private in a subclass? Why is super.paintComponent(g) invoked in line 21 in Listing 15.1 and in line 31 in Listing 15.3?
15.5Can you draw things on any Swing GUI component? Why should you use a panel as a canvas for drawings rather than a label or a button?
Sections 15.4-15.7
15.6Describe the methods for drawing strings, lines, rectangles, round-cornered rectangles, 3D rectangles, ovals, arcs, polygons, and polylines.
15.7Describe the methods for filling rectangles, round-cornered rectangle, ovals, arcs, and polygons.
15.8How do you get and set colors and fonts in a Graphics object?
15.9Write a statement to draw the following shapes:
■Draw a thick line from (10, 10) to (70, 30). You can draw several lines next to each other to create the effect of one thick line.
■Draw/fill a rectangle of width 100 and height 50 with the upper-left corner at (10, 10).
■Draw/fill a round-cornered rectangle with width 100, height 200, corner horizontal diameter 40, and corner vertical diameter 20.
■Draw/fill a circle with radius 30.
■Draw/fill an oval with width 50 and height 100.
■Draw the upper half of a circle with radius 50.
■Draw/fill a polygon connecting the following points: (20, 40), (30, 50), (40,
90), (90, 10), (10, 30).
Sections 15.8–15.10
15.10How do you find the leading, ascent, descent, and height of a font? How do you find the exact length in pixels of a string in a Graphics object?
15.11If message is not initialized in line 8 in Listing 15.8, MessagePanel.java, what will happen when you create a MessagePanel using its no-arg constructor?
15.12The following program is supposed to display a message on a panel, but nothing is displayed. There are problems in lines 2 and 14. Correct them.
1 public class TestDrawMessage extends javax.swing.JFrame {
2 public void TestDrawMessage() {
3add(new DrawMessage());
4 |
} |
5 |
|
6public static void main(String[] args) {
7javax.swing.JFrame frame = new TestDrawMessage();
8frame.setSize(100, 200);
9frame.setVisible(true);
10}
11}
13class DrawMessage extends javax.swing.JPanel {
14protected void PaintComponent(java.awt.Graphics g) {
15super.paintComponent(g);
16g.drawString("Welcome to Java", 20, 20);
17}
18}
Sections 15.11–15.12
15.13 How do you create an Image object from the ImageIcon object?
Programming Exercises 527
15.14How do you create an ImageIcon object from an Image object?
15.15Describe the drawImage method in the Graphics class.
15.16Explain the differences between displaying images in a JLabel and in a JPanel.
15.17Which package contains ImageIcon, and which contains Image?
PROGRAMMING EXERCISES
Sections 15.2–15.7
15.1* (Displaying a 3 * 3 grid) Write a program that displays a 3 * 3 grid, as shown in Figure 15.27(a). Use red color for vertical lines and blue for horizontals.
(a) |
(b) |
(c) |
FIGURE 15.27 (a) Exercise 15.1 displays a grid. (b) Exercise 15.2 displays two objects of
OvalButton. (c) Exercise 15.3 displays a checkerboard.
15.2** (Creating a custom button class) Develop a custom button class named OvalButton that extends JButton and displays the button text inside an oval. Figure 15.27(b) shows two buttons created using the OvalButton class.
15.3* (Displaying a checkerboard) Exercise 12.10 displays a checkerboard in which each white and black cell is a JButton. Rewrite a program that draws a checkerboard on a JPanel using the drawing methods in the Graphics class, as shown in Figure 15.27(c).
15.4* (Displaying a multiplication table) Write a program that displays a multiplication table in a panel using the drawing methods, as shown in Figure 15.28(a).
(a) |
(b) |
FIGURE 15.28 (a) Exercise 15.4 displays a multiplication table. (b) Exercise 15.5 displays numbers in a triangle formation.
15.5** (Displaying numbers in a triangular pattern) Write a program that displays numbers in a triangular pattern, as shown in Figure 15.28(b). The number of lines in the display changes to fit the window as the window resizes.
15.6** (Improving FigurePanel) The FigurePanel class in Listing 15.3 can display lines, rectangles, round-cornered rectangles, and ovals. Add appropriate new code
528 Chapter 15 Graphics
in the class to display arcs and polygons. Write a test program to display the shapes as shown in Figure 15.29(a) using the new FigurePanel class.
(a) |
(b) |
(c) |
FIGURE 15.29 (a) Four panels of geometric figures are displayed in a frame of GridLayout. (b) TicTacToe cells randomly display X, O, or nothing. (c) Exercise 15.8 draws an octagon.
15.7** (Displaying a TicTacToe board) Create a custom panel that displays X, O, or nothing. What to display is randomly decided whenever a panel is repainted. Use the Math.random() method to generate an integer 0, 1, or 2, which corresponds to displaying X, O, or nothing. Create a frame that contains nine custom panels, as shown in Figure 15.29(b).
15.8** (Drawing an octagon) Write a program that draws an octagon, as shown in Figure 15.29(c).
15.9* (Creating four fans) Write a program that places four fans in a frame of GridLayout with two rows and two columns, as shown in Figure 15.30(a).
(a) |
(b) |
(c) |
FIGURE 15.30 (a) Exercise 15.9 draws four fans. (b) Exercise 15.10 draws a cylinder. (c)
Exercise 15.11 draws a diagram for function f1x2 = x2.
15.10* (Displaying a cylinder) Write a program that draws a cylinder, as shown in Figure 15.30(b).
15.11** (Plotting the square function) Write a program that draws a diagram for the function f1x2 = x2 (see Figure 15.30(c)).
Hint: Add points to a polygon p using the following loop:
double scaleFactor = 0.1;
for (int x = -100; x <= 100; x++) {
p.addPoint(x + 200, 200 - (int)(scaleFactor * x * x));
}
Programming Exercises 529
Connect the points using g.drawPolyline(p.xpoints, p.ypoints, p.npoints) for a Graphics object g. p.xpoints returns an array of x-coordinates, p.ypoints an array of y-coordinates, and p.npoints the number of points in Polygon object p.
15.12** (Plotting the sine function) Write a program that draws a diagram for the sine function, as shown in Figure 15.31(a).
Video Note
Plot a sine function
(a) |
(b) |
FIGURE 15.31 (a) Exercise 15.12 draws a diagram for function f (x)= sin(x). (b) Exercise 15.13 draws the sine and cosine functions.
Hint: The Unicode for p is \u03c0. To display - 2p, use g.drawString ("-2\u03c0", x, y). For a trigonometric function like sin(x), x is in radians. Use the following loop to add the points to a polygon p:
for (int x = -100; x <= 100; x++) { p.addPoint(x + 200,
100 - (int)(50 * Math.sin((x / 100.0) * 2 * Math.PI)));
}
- 2p is at (100, 100), the center of the axis is at (200, 100), and 2p is at (300, 100). Use the drawPolyline method in the Graphics class to connect the points.
15.13** (Plotting functions using abstract methods) Write an abstract class that draws the diagram for a function. The class is defined as follows:
public abstract class AbstractDrawFunction extends JPanel { /** Polygon to hold the points */
private Polygon p = new Polygon();
protected AbstractDrawFunction () { drawFunction();
}
/** Return the y-coordinate */ abstract double f(double x);
/** Obtain points for x-coordinates 100, 101, ..., 300 */ public void drawFunction() {
for (int x = -100; x <= 100; x++) { p.addPoint(x + 200, 200 - (int)f(x));
}
}
/** Implement paintComponent to draw axes, labels, and * connecting points
*/
protected void paintComponent(Graphics g) { // To be completed by you
}
}
530 Chapter 15 Graphics
Test the class with the following functions:
f(x) = x2; f(x) = sin(x); f(x) = cos(x); f(x) = tan(x);
f(x) = cos(x) + 5sin(x); f(x) = 5cos(x) + sin(x); f(x) = log(x) + x2;
For each function, create a class that extends the AbstractDrawFunction class and implements the f method. Figure 15.31(b) displays the drawings for the sine function and the cosine function.
15.14** (Displaying a bar chart) Write a program that uses a bar chart to display the percentages of the overall grade represented by projects, quizzes, midterm exams, and the final exam, as shown in Figure 15.1(a). Suppose that projects take 20 percent and are displayed in red, quizzes take 10 percent and are displayed in blue, midterm exams take 30 percent and are displayed in green, and the final exam takes 40 percent and is displayed in orange.
15.15** (Displaying a pie chart) Write a program that uses a pie chart to display the percentages of the overall grade represented by projects, quizzes, midterm exam, and the final exam, as shown in Figure 15.32(a). Suppose that projects take 20 percent and are displayed in red, quizzes take 10 percent and are displayed in blue, midterm exam takes 30 percent and are displayed in green, and the final exam takes 40 percent and is displayed in orange.
15.16(Obtaining font information) Write a program that displays the message “Java is fun” in a panel. Set the panel’s font to TimesRoman, bold, and 20 pixel. Display the font’s leading, ascent, descent, height, and the string width as a tool tip text for the panel, as shown in Figure 15.32(b).
(a) |
(b) |
(c) |
FIGURE 15.32 (a) Exercise 15.15 uses a pie chart to show the percentages of projects, quizzes, midterm exam, and final exam in the overall grade. (b) Exercise 15.16 displays font properties in a tool tip text. (c) Exercise 15.17 draws a sketch for the hangman game.
15.17(Game: hangman) Write a program that displays a drawing for the popular hangman game, as shown in Figure 15.32(c).
15.18(Using the StillClock class) Write a program that displays two clocks. The hour, minute, and second values are 4, 20, 45 for the first clock and 22, 46, 15 for the second clock, as shown in Figure 15.33(a).
Programming Exercises 531
(a) |
(b) |
(c) |
(d) |
FIGURE 15.33 (a) Exercise 15.18 displays two clocks. (b) Exercise 15.19 displays a clock with random hour and minute values. (c) Exercise 15.23 displays a rectanguloid. (d) Exercise 15.24 simulates a bean machine.
15.19* (Random time) Modify the StillClock class with three new Boolean properties— hourHandVisible, minuteHandVisible, and secondHandVisible—and their associated accessor and mutator methods. You can use the set methods to make a hand visible or invisible. Write a test program that displays only the hour and minute hands. The hour and minute values are randomly generated. The hour is between 0 and 11, and the minute is either 0 or 30, as shown in Figure 15.33(b).
15.20** (Drawing a detailed clock) Modify the StillClock class in §15.12, “Case Study: The StillClock Class,” to draw the clock with more details on the hours and minutes, as shown in Figure 15.1(b).
15.21** (Displaying a TicTacToe board with images) Rewrite Exercise 12.7 to display an image in a JPanel instead of displaying an image icon in a JLabel.
15.22** (Displaying a STOP sign) Write a program that displays a STOP sign, as shown in Figure 15.1(c). The hexagon is in red and the sign is in white.
(Hint: See Listing 15.5, DrawPolygon.java, and Listing 15.6, TestCenterMessage.java.)
15.23(Displaying a rectanguloid) Write a program that displays a rectanguloid, as shown in Figure 15.33(c). The cube should grow and shrink as the frame grows or shrinks.
15.24** (Game: bean machine) Write a program that displays a bean machine introduced in Exercise 6.21. The bean machine should be centered in a resizable panel, as shown in Figure 15.33(d).
15.25**(Geometry: displaying an n-sided regular polygon) Create a subclass of
JPanel, named RegularPolygonPanel, to paint an n-sided regular polygon. The class contains a property named numberOfSides, which specifies the number of sides in the polygon. The polygon is centered at the center of the panel. The size of the polygon is proportional to the size of the panel. Create a pentagon, hexagon, heptagon, and octagon, nonagon, and decagon from RegularPolygonPanel and display them in a frame, as shown in Figure 15.34(a).
15.26(Using the MessagePanel class) Write a program that displays four messages, as shown in Figure 15.34(b).
15.27** (Displaying a graph) A graph consists of vertices and edges that connect vertices. Write a program that reads a graph from a file and displays it on a panel. The first line in the file contains a number that indicates the number of vertices (n). The vertices are labeled as 0, 1, Á , n-1. Each subsequent line, with the
532 Chapter 15 Graphics
(a) |
(b) |
FIGURE 15.34 (a) Exercise 15.25 displays several n-sided polygons. (b) Exercise 15.26 uses MessagePanel to display four strings.
format u x y v1, v2, ..., describes that the vertex u is located at position (x, y) with edges (u, v1), (u, v2), etc. Figure 15.35(a) gives an example of the file for a graph. Your program prompts the user to enter the name of the file, reads data from the file, and displays the graph on a panel, as shown in Figure 15.35(b).
File |
|
|
|
|
0 |
1 |
|
|
6 |
|
|
|
|
|
|
||
|
|
|
|
|
|
|
|
|
0 |
30 |
30 |
1 |
2 |
|
|
|
|
1 |
90 |
30 |
0 |
3 |
|
2 |
3 |
|
2 |
30 |
90 |
0 |
3 |
4 |
|
||
3 |
90 |
90 |
1 |
2 |
4 |
5 |
|
|
4 |
30 |
150 |
2 |
|
3 |
5 |
|
|
5 |
90 |
150 |
3 |
|
4 |
4 |
5 |
|
|
|
|
|
|
|
|
||
|
|
|
|
|
|
(a) |
(b) |
(c) |
FIGURE 15.35 (a)-(b) The program reads the information about the graph and displays it visually.
(c) The program displays an arrow line.
15.28** (Drawing an arrow line) Write a static method that draws an arrow line from a starting point to an ending point using the following method header:
public static void drawArrowLine(int x1, int y1, int x2, int y2, Graphics g)
Write a test program that randomly draws an arrow line when the Draw Random
Arrow Line button is clicked, as shown in Figure 15.35(c).
CHAPTER 16
EVENT-DRIVEN PROGRAMMING
Objectives
■To describe events, event sources, and event classes (§16.2).
■To define listener classes, register listener objects with the source object, and write the code to handle events (§16.3).
■To define listener classes using inner classes (§16.4).
■To define listener classes using anonymous inner classes (§16.5).
■To explore various coding styles for creating and registering listeners (§16.6).
■To get input from text field upon clicking a button (§16.7).
■To write programs to deal with WindowEvent (§16.8).
■To simplify coding for listener classes using listener interface adapters (§16.9).
■To write programs to deal with MouseEvent (§16.10).
■To write programs to deal with KeyEvent (§16.11).
■To use the javax.swing.Timer class to control animations (§16.12).