Java Reference
In-Depth Information
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
104 Calendar calendar =
new
GregorianCalendar();
105
106
get current time
// 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
112 @Override
113
override
getPreferredSize
public
Dimension getPreferredSize() {
114
return new
Dimension(
200
,
200
);
115 }
116 }
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 a new clock. The
paintComponent
method displays the clock in proportion to the panel width (
getWidth()
)
and height (
getHeight()
) (lines 60-63 in
StillClock
).
You can draw images in a graphics context.
Key
Point
You learned how to create image icons and display them in labels and buttons in Section 12.10,
Image Icons. For example, the following statements create an image icon and display it in a label:
ImageIcon imageIcon =
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();
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 13.22.
ImageObserver
specifies a GUI component for receiving notifications of image informa-
tion 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 13.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 13.23.