RosettaCodeData/Task/Draw-a-clock/Java/draw-a-clock.java

82 lines
2.4 KiB
Java
Raw Permalink Normal View History

2015-02-20 09:02:09 -05:00
import java.awt.*;
import java.awt.event.*;
2015-11-18 06:14:39 +00:00
import static java.lang.Math.*;
import java.time.LocalTime;
2015-02-20 09:02:09 -05:00
import javax.swing.*;
class Clock extends JPanel {
2015-11-18 06:14:39 +00:00
final float degrees06 = (float) (PI / 30);
2015-02-20 09:02:09 -05:00
final float degrees30 = degrees06 * 5;
final float degrees90 = degrees30 * 3;
2015-11-18 06:14:39 +00:00
final int size = 590;
final int spacing = 40;
2015-02-20 09:02:09 -05:00
final int diameter = size - 2 * spacing;
2015-11-18 06:14:39 +00:00
final int cx = diameter / 2 + spacing;
final int cy = diameter / 2 + spacing;
2015-02-20 09:02:09 -05:00
public Clock() {
setPreferredSize(new Dimension(size, size));
setBackground(Color.white);
2015-11-18 06:14:39 +00:00
new Timer(1000, (ActionEvent e) -> {
repaint();
2015-02-20 09:02:09 -05:00
}).start();
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
2015-11-18 06:14:39 +00:00
drawFace(g);
2015-02-20 09:02:09 -05:00
2015-11-18 06:14:39 +00:00
final LocalTime time = LocalTime.now();
int hour = time.getHour();
int minute = time.getMinute();
int second = time.getSecond();
2015-02-20 09:02:09 -05:00
2015-11-18 06:14:39 +00:00
float angle = degrees90 - (degrees06 * second);
2015-02-20 09:02:09 -05:00
drawHand(g, angle, diameter / 2 - 30, Color.red);
2015-11-18 06:14:39 +00:00
float minsecs = (minute + second / 60.0F);
2015-02-20 09:02:09 -05:00
angle = degrees90 - (degrees06 * minsecs);
drawHand(g, angle, diameter / 3 + 10, Color.black);
2015-11-18 06:14:39 +00:00
float hourmins = (hour + minsecs / 60.0F);
2015-02-20 09:02:09 -05:00
angle = degrees90 - (degrees30 * hourmins);
drawHand(g, angle, diameter / 4 + 10, Color.black);
}
2015-11-18 06:14:39 +00:00
private void drawFace(Graphics2D g) {
g.setStroke(new BasicStroke(2));
g.setColor(Color.white);
g.fillOval(spacing, spacing, diameter, diameter);
g.setColor(Color.black);
g.drawOval(spacing, spacing, diameter, diameter);
}
2015-02-20 09:02:09 -05:00
private void drawHand(Graphics2D g, float angle, int radius, Color color) {
2015-11-18 06:14:39 +00:00
int x = cx + (int) (radius * cos(angle));
int y = cy - (int) (radius * sin(angle));
2015-02-20 09:02:09 -05:00
g.setColor(color);
2015-11-18 06:14:39 +00:00
g.drawLine(cx, cy, x, y);
2015-02-20 09:02:09 -05:00
}
public static void main(String[] args) {
2015-11-18 06:14:39 +00:00
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Clock");
f.setResizable(false);
f.add(new Clock(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
2015-02-20 09:02:09 -05:00
});
}
}