Files
javalab/P8.java
Amneesh Singh 14898356a8 P6-P15: init
Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
2023-06-05 03:15:38 +05:30

85 lines
2.5 KiB
Java

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Calendar;
public class P8 extends Applet implements Runnable {
Thread t = null;
boolean threadSuspended;
int hours = 0, minutes = 0, seconds = 0;
public void init() {
setBackground(Color.white);
}
public void start() {
if (threadSuspended) {
threadSuspended = false;
synchronized (this) {
notify();
}
}
if (t == null) {
t = new Thread(this);
threadSuspended = false;
t.start();
}
}
public void stop() {
threadSuspended = true;
}
public void run() {
try {
while (true) {
Calendar cal = Calendar.getInstance();
hours = cal.get(Calendar.HOUR_OF_DAY) % 12;
if (hours == 0)
hours += 1;
minutes = cal.get(Calendar.MINUTE);
seconds = cal.get(Calendar.SECOND);
repaint();
Thread.sleep(1000);
if (threadSuspended) {
synchronized (this) {
while (threadSuspended)
wait();
}
}
}
} catch (InterruptedException e) {
System.out.println("Process interrupted");
}
}
void drawHand(double angle, int radius, Graphics g) {
angle -= 0.5 * Math.PI;
int x = (int) (radius * Math.cos(angle));
int y = (int) (radius * Math.sin(angle));
g.drawLine(getWidth() / 2, getHeight() / 2, getWidth() / 2 + x, getHeight() / 2 + y);
}
public void paint(Graphics g) {
int radius = Math.min(getWidth(), getHeight()) / 2 - 10;
g.setColor(Color.blue);
g.drawOval(getWidth() / 2 - radius, getHeight() / 2 - radius, 2 * radius, 2 * radius);
g.setColor(Color.black);
g.fillOval(getWidth() / 2 - 5, getHeight() / 2 - 5, 10, 10);
double hourAngle = (hours + minutes / 60.0) * (2 * Math.PI / 12) - 0.5 * Math.PI;
double minuteAngle = (minutes + seconds / 60.0) * (2 * Math.PI / 60) - 0.5 * Math.PI;
double secondAngle = (seconds * 2 * Math.PI / 60) - 0.5 * Math.PI;
g.setColor(Color.black);
drawHand(hourAngle, radius / 2, g);
g.setColor(Color.gray);
drawHand(minuteAngle, (int) (0.8 * radius), g);
g.setColor(Color.red);
drawHand(secondAngle, (int) (0.9 * radius), g);
}
}