/* * AnalogClock.java * Displays the current time on an old style analog clock */ /** * Created 11/2011 * By Randall Twede */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.Calendar; import java.net.*; import java.awt.image.BufferedImage; public class AnalogClock extends JPanel implements ActionListener { private Timer timer = new Timer(1000,this); private URL url; private Image face; private int second; // the second private int minute; // the minute private int hour; // the hour private double secondAngle; // the angle of the second hand private double minuteAngle; // the angle of the minute hand private double hourAngle; // the angle of the hour hand private int secondLength; // the length of the second hand private int minuteLength; // the length of the minute hand private int hourLength; // the length of the hour hand private Point origin; public AnalogClock(int minuteHandLength) { secondLength = minuteHandLength; minuteLength = minuteHandLength; hourLength = (int)(minuteHandLength * 0.75); origin = new Point(minuteHandLength, minuteHandLength); timer.start(); } public AnalogClock(int minuteHandLength, Image clockFace) { secondLength = minuteHandLength; minuteLength = minuteHandLength; hourLength = (int)(minuteHandLength * 0.75); face = clockFace; origin = new Point((int)face.getWidth(null)/2, (int)face.getHeight(null)/2); timer.start(); } public Dimension getPreferredSize() { Dimension d = null; if(face != null) { d = new Dimension(face.getWidth(null), face.getHeight(null)); } else { d = new Dimension(minuteLength * 2, minuteLength * 2); } return d; } public void actionPerformed(ActionEvent e) { getTime(); hourAngle = (Math.PI/2 - hour * (Math.PI / 6)) - minute * (Math.PI / 360); minuteAngle = Math.PI/2 - minute * (Math.PI / 30); secondAngle = Math.PI/2 - second * (Math.PI / 30); repaint(); } public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(face, 0, 0, null); Graphics2D g2 = (Graphics2D)g; RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHints(rh); g2.setStroke(new BasicStroke(4)); g2.drawLine(origin.x,origin.y,(int)(origin.x + Math.cos(minuteAngle) * minuteLength),(int)(origin.y - Math.sin(minuteAngle) * minuteLength)); g2.drawLine(origin.x,origin.y,(int)(origin.x + Math.cos(hourAngle) * hourLength),(int)(origin.y - Math.sin(hourAngle) * hourLength)); g2.setStroke(new BasicStroke(1)); g2.setColor(Color.RED); g2.drawLine(origin.x,origin.y,(int)(origin.x + Math.cos(secondAngle) * secondLength),(int)(origin.y - Math.sin(secondAngle) * secondLength)); } private void getTime() { Calendar now = Calendar.getInstance(); hour = now.get(Calendar.HOUR); minute = now.get(Calendar.MINUTE); second = now.get(Calendar.SECOND); } }