import javax.swing.JFrame; ///driver class public class Stopwatch { public static void main(String[] args) { JFrame frame = new JFrame("Stopwatch 9.10 Haris Cengic"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(new StopWatchPanel()); frame.pack(); frame.setVisible(true); } }; //--------------------------------------------------------------// import javax.swing.JPanel; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JLabel; import javax.swing.Timer; import java.awt.Color; import java.awt.Font; import java.awt.Dimension; import java.awt.Graphics; public class StopWatchPanel extends JPanel { private final int START = 100; //START will be set to 100, keeps the timer accurate private final int WIDTH = 500, HEIGHT = 110; //size of jpanel private final int SIZE = 80; // size of the font for the stopwatch private int second; //shows the current second private boolean hasstarted; //check if the timer is running private Timer timer; //new timer private JButton start, stop, clear; //buttons private JLabel time; //shows the time in seconds public StopWatchPanel() { timer = new Timer(START, new TimerListener()); second = 0; hasstarted = true; //set the time to 0 and start the timer start = new JButton("Start");//new button for start option start.addActionListener(new ButtonListener()); clear = new JButton("Clear");//new button for clear clear.addActionListener(new ButtonListener()); time = new JLabel("0.0"); time.setFont(new Font("Arial", Font.ITALIC, SIZE)); add(start); add(clear); add(time); setPreferredSize(new Dimension(WIDTH, HEIGHT)); setBackground(Color.red); } public final void paintComponent(Graphics page) { super.paintComponent(page); //super.paintCompenent invokes paintComponent and it overwrites whatever is there final int milli = 10; //base 10, dividing second by 10 and %10 to display the time in seconds AND milliseconds time.setText(" " + second / milli + "." + second % milli + " "); } private class ButtonListener implements ActionListener { //this class tells if the timer is running and based //on that changes the button from 'start' to 'stop' //also it defines what 'clear' does public void actionPerformed(ActionEvent event) { if (event.getSource() == start) { if (hasstarted) { hasstarted = false; timer.start(); start.setText("Stop"); } else { hasstarted = true; timer.stop(); start.setText("Start"); } } else if (event.getSource() == clear) { second = 0; hasstarted = true; timer.stop(); start.setText("Start"); } repaint(); } } private class TimerListener implements ActionListener { public void actionPerformed(ActionEvent event) { second++; repaint(); } } } //----------------------------------------------------------------------------//