I am trying to implement a simple analogue clock in java. My clock successfully displays the time when I first run the program, however upon opening the time remains the same and none of the drawing updates and it freezes. I don't understand why it is not working and I have looked through the forum trying to find someone with a similar problem and cannot. If anyone can find where I am going wrong I would greatly appreciate it, thanks
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing. JPanel;
public class ClockFace extends JPanel {
Date date = new Date();
private BufferedImage clockFace;
public ClockFace() {
this.init();
this.startClock();
}
private void init() {
JFrame window = new JFrame("Clock");
window.setContentPane(this);
this.setPreferredSize(new Dimension(600,600));
window.pack();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.setLocationRelativeTo(null);
}
//Draws the image to the ClockFace panel
public void paintComponent(Graphics g) {
Graphics2D twoD = (Graphics2D) g;
twoD.drawImage(clockFace, 0, 0, null);
}
public void startClock() {
while(true) {
int seconds = date.getSeconds();
int minutes = date.getMinutes();
int hours = date.getHours();
clockFace = new BufferedImage(600,600,BufferedImage.TYPE_INT_ARGB);
Graphics2D twoD = clockFace.createGraphics();
twoD.setColor(Color.BLACK);
twoD.fillRect(0, 0, 600, 600);
twoD.setColor(Color.WHITE);
twoD.translate(300,300);
//Drawing the hour markers
for(int i=0; i<12; i++) {
twoD.drawLine(0, -260, 0, -300);
twoD.rotate(Math.PI/6);
}
twoD.rotate(seconds*Math.PI/30);
twoD.drawLine(0, 0, 0, -290);
twoD.rotate(2*Math.PI-seconds*Math.PI/30);
twoD.rotate(minutes*Math.PI/30);
twoD.setStroke(new BasicStroke(3));
twoD.drawLine(0, 0, 0, -250);
twoD.rotate(2*Math.PI-minutes*Math.PI/30);
twoD.rotate(hours*Math.PI/6);
twoD.setStroke(new BasicStroke(6));
twoD.drawLine(0, 0, 0, -200);
repaint();
//Pausing until the next "tick"
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
get
methods ofDate
are deprecated. Instead I recommend you useLocalTime
, one of the classes fromjava.time
, the modern Java date and time API. Also, are you ever changing the value ofdate
? Link: Oracle Tutorial: Date Time.