import javax.swing.Timer; import javax.swing.*; import java.util.*; import java.awt.*; import java.awt.event.*; public class Clock extends JPanel implements MouseListener, ActionListener { private String message; private Timer ticker; private int hours, mins, secs; private Font font; public static final int SIZE = 50; public static final int WIDTH = 500; public static final int HEIGHT = 500; public void reset() { message =""; ticker.restart(); repaint(); } public Clock() // constructor { font = new Font("Helvetica", Font.BOLD, 36); ticker = new Timer (1000,this); ticker.start(); message = ""; reset(); setTime(8,30,0); addMouseListener(this); } public void updateTime() { secs++; if (secs>=60){ secs=0; mins++; } if (mins>=60){ mins=0; hours++; } if (hours>24) hours=0; } @Override public void actionPerformed(ActionEvent e) { if (e.getSource()==ticker){ updateTime(); repaint(); } else {//must have been another thing generating the event } } public void setTicker( Timer t) { ticker = t; } public void paintComponent(Graphics g) { setBackground(new Color(255,220,200) ); super.paintComponent(g); g.setColor(Color.BLACK); g.drawString(message, 20, 20); g.setFont(font); g.drawString ( toString(), getWidth()/3, getHeight()/2); } public void setTime(int h, int m, int s) { hours=h; mins=m; secs=s; } public String toString() { String m = ""+mins; if (mins<10) m="0"+m; String s = ""+secs; if (secs<10) s="0"+s; return hours+":"+m+":"+s; } public static void main(String[] args) { JFrame window = new JFrame(); window.setSize(WIDTH, HEIGHT); Container c = window.getContentPane(); c.add(new Clock()); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setVisible(true); } public void mouseReleased(MouseEvent e) { int x = e.getX(); int y = e.getY(); setTime(0,0,0); repaint(); } public void mousePressed(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } }