forked from kishanrajput23/Java-Projects-Collections
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnalog Clock.java
73 lines (63 loc) · 2.46 KB
/
Analog Clock.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class AnalogClock extends JPanel {
private int radius;
private int centerX;
private int centerY;
public AnalogClock(int radius) {
this.radius = radius;
this.setPreferredSize(new Dimension(2 * radius, 2 * radius));
Timer timer = new Timer(1000, new ClockListener());
timer.start();
}
private class ClockListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
private void drawClockHand(Graphics g, int handLength, int angle, int value) {
int x = (int) (centerX + handLength * Math.sin(Math.toRadians(angle)));
int y = (int) (centerY - handLength * Math.cos(Math.toRadians(angle)));
g.drawLine(centerX, centerY, x, y);
if (value != -1) {
g.drawString(Integer.toString(value), x, y);
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
centerX = getWidth() / 2;
centerY = getHeight() / 2;
Calendar now = new GregorianCalendar();
int hour = now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
g.setColor(Color.BLACK);
g.drawOval(centerX - radius, centerY - radius, 2 * radius, 2 * radius);
g.drawString("12", centerX - 5, centerY - radius + 15);
g.drawString("3", centerX + radius - 10, centerY + 5);
g.drawString("6", centerX - 5, centerY + radius - 5);
g.drawString("9", centerX - radius + 5, centerY + 5);
int hourAngle = (360 / 12) * (hour % 12) - 90;
int minuteAngle = (360 / 60) * minute - 90;
int secondAngle = (360 / 60) * second - 90;
g.setColor(Color.BLUE);
drawClockHand(g, (int) (0.5 * radius), hourAngle, hour);
g.setColor(Color.GREEN);
drawClockHand(g, (int) (0.8 * radius), minuteAngle, minute);
g.setColor(Color.RED);
drawClockHand(g, (int) (0.9 * radius), secondAngle, second);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Analog Clock");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new AnalogClock(200));
frame.pack();
frame.setVisible(true);
}
}