I am trying to develop an application that can display four clocks in a frame that update at the following intervals: 1 second, 5 seconds, 30 seconds and 60 seconds, here is the code so far.
Timer.java
import javax.swing.*;
public class Timer extends Thread {
private int waitTime;
private JPanel panel;
private boolean active = true;
public Timer (int waitTime, JPanel panel) {
/** Correct the two lines of code below **/
waitTime = waitTime;
panel = panel;
}
// Overridden run method. Will keep looping until active is false
public void run () {
while (active) {
try {
sleep(waitTime);
}
catch (InterruptedException e) {
// any exceptions will be caught but ignored
}
panel.repaint(); // Force panel to be redrawn
}
}
public void stopTimer() {
active = false;
}
}
ClockPanel.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Date;
import java.text.SimpleDateFormat;
public class ClockPanel extends JPanel {
private static int WIDTH = 500;
private static int HEIGHT = 200;
static final SimpleDateFormat formatter
= new SimpleDateFormat ("HH:mm:ss");
public ClockPanel (int milli) {
//
// Create and start a new thread
this.setBorder(BorderFactory.createLineBorder(Color.white));
Timer timer = new Timer (milli, this);
timer.start();
}
public static void main (final String[] args ) {
JFrame clockFrame = new JFrame ("Clock");
JPanel mainPanel = new JPanel (new GridLayout(2,2));
clockFrame.getContentPane().add(mainPanel);
mainPanel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
ClockPanel p1 = new ClockPanel(1000);
/** create additional ClockPanel objects **/
/** add the individual ClockPanel objects to the main panel **/
clockFrame.pack ();
clockFrame.setVisible(true);
clockFrame.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0); } } );
}
public void paint (final Graphics g) {
super.paint(g); // Clear the panel
Font big = new Font("Serif", Font.PLAIN, 40);
g.setFont(big);
// Provide the parameters to the drawstring method below
g.drawString(...............);
}
}