Write a program that teaches children how to read a clock. Input the hour and minute. Accept only numbers between 0 and 12 for hour and between 0 and 59 for minute. Print out an appropriate error message for an invalid input value. Draw a clock that looks something like this:
To draw a clock hand, you use the drawLine method of the Graphics class.
The endpoints of the line are determined as follows:
The value for constant K determines the length of the clock hand. Make the K larger for the minute hand than for the hour hand. The angle is expressed in radians. The angle min of the minute hand is computed as
and the angle hr of the hour hand is computed as
where Hour and Minute are input values. The values 6.0 and 30.0 designate the degrees for 1 min and 1 h (i.e., the minute hand moves 6 degrees in 1 min and the hour hand moves 30.0 degrees in 1 h). The factor π/180 converts a degree into the radian equivalent. You can draw the clock on the content pane of a frame window by getting the content pane’s Graphic object as described in the chapter. Here’s some sample code:
import javax.swing.*; import java.awt.*; //for Graphics
...
JFrame win;
Container contentPane;
Graphics g;
win = new JFrame(); win.setSize(300, 300); win.setLocation(100,100); win.setVisible(true);
contentPane = win.getContentPane(); g = contentPane.getGraphics(); g.drawOval(50,50,200,200);
Also, please refer to the You Might Want to Know box on p. 259 if you want the drawing to remain on the window (instead of disappearing when the window is minimized, for example).
Already registered? Login
Not Account? Sign up
Enter your email address to reset your password
Back to Login? Click here