Make Analog Clock in Java
Make Analog Clock in Java - YouTube
________________________________________________ How to Make Analog Clock in Java?
package SimpleProjects;
import java.awt.*;
import java.awt.event.*;
import static java.lang.Math.*;
import java.time.LocalTime;
import javax.swing.*;
public class AnalogClock extends JPanel{
final float degrees06 = (float) (PI / 30);
final float degrees30 = degrees06 * 5;
final float degrees90 = degrees30 * 3;
final int size = 300;
final int spacing = 10;
final int diameter = size - 2 * spacing;
final int cX = diameter / 2 + spacing;
final int cY = diameter / 2 + spacing;
public AnalogClock() {
setPreferredSize(new Dimension(size, size));
setBackground(Color.CYAN);
new Timer(1000, (ActionEvent e) ->{
repaint();
}).start();
}
@Override
public void paintComponent(Graphics g2Dg) {
super.paintComponent(g2Dg);
Graphics2D g2D = (Graphics2D) g2Dg;
g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
drawFace(g2D);
final LocalTime time = LocalTime.now();
int hour = time.getHour();
int minute = time.getMinute();
int second = time.getSecond();
float angle = degrees90 - (degrees06 * second);
drawHand(g2D, angle, diameter / 2 - 30, Color.red);
float minsecs = (minute + second / 60.0F);
angle = degrees90 - (degrees06 * minsecs);
drawHand(g2D, angle, diameter / 3 + 10, Color.black);
float hourmin = (hour + minsecs / 60.0F);
angle = degrees90 - (degrees30 * hourmin);
drawHand(g2D, angle, diameter / 4 + 10, Color.black);
}
private void drawHand(Graphics2D g2d, float angle, int radius, Color color) {
int x = cX + (int)(radius * cos(angle));
int y = cY - (int)(radius * sin(angle));
g2d.setColor(color);
g2d.drawLine(cX, cY, x, y);
}
private void drawFace(Graphics2D g2d) {
g2d.setStroke(new BasicStroke(2));
g2d.setColor(Color.white);
g2d.fillOval(spacing, spacing, diameter, diameter);
g2d.setColor(Color.black);
g2d.drawOval(spacing, spacing, diameter, diameter);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() ->{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Analog Clock");
frame.setResizable(false);
frame.add(new AnalogClock(), BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
________________________________________________
Dark Hers
YouTube
https://instagram.com/darkhers
https://www.facebook.com/darkhers
TikTok
https://www.tiktok.com/@darkhers
https://www.pinterest.co.uk/darkhers
Comments
Post a Comment