Create a class for a watch. It should have private hour, minute, and seconds as
ID: 3679360 • Letter: C
Question
Create a class for a watch. It should have private hour, minute, and seconds as fields. It
should have 4 constructors: one that takes no fields and sets the time to 12:00:00, one that takes
only the hour field as an input and sets the minutes and seconds to 0, one that takes the hour and
the minute fields as input parameters and sets the seconds to 0, and then one
that sets all 3 fields.
There should be a “Set” method that sets the hour, the minute, and the seconds field. There should be a toString()
method that returns a string that represents the current time. Finally, you should create a “main” class that has
a main method in it and creates a watch object. Test your 4 constructors. Test your methods.
Dialog Boxes: If you want to input data by having the user type something in,
use a dialog box. To use a dialog box:
First at the very top of the class file,
import javax.swing.JOptionPane;
Then in the method, create a string variable that will hold the input from
the dialog box:
String svar = JOptionPane.
showInputDialog(“Enter yourinfo”);
And finally, you’ll have to convert the svar to a double:
double xvar = Double.parseDouble(svar);
Explanation / Answer
import java.awt.*;
import java.applet.*;
import java.applet.*;
import java.awt.*;
import java.util.*;
public class Clock extends Applet implements Runnable{
Thread t,t1;
public void start(){
t = new Thread(this);
t.start();
}
public void run(){
t1 = Thread.currentThread();
while(t1 == t){
repaint();
try{
t1.sleep(1000);
}
catch(InterruptedException e){}
}
}
public void paint(Graphics g){
Calendar cal = new GregorianCalendar();
String hour = String.valueOf(cal.get(Calendar.HOUR));
String minute = String.valueOf(cal.get(Calendar.MINUTE));
String second = String.valueOf(cal.get(Calendar.SECOND));
g.drawString(hour + ":" + minute + ":" + second, 20, 30);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.