import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Stop2 extends JApplet
{
public Stop2 ( )
{
StopWatchRunner2 watch = new StopWatchRunner2();
watch.setBackground(Color.gray);
getContentPane().add(watch, BorderLayout.CENTER);
}
}
class StopWatchRunner2 extends JPanel implements ActionListener
{
private boolean running, paused;
private long startTime;
private double seconds, time;
private Timer timer;
private JButton starter, pauser, reset;
private Font mine;
public StopWatchRunner2()
{
setLayout(null);
setUpValues ( );
mine = new Font ( "Serif", Font.PLAIN, 48 );
starter = new JButton ( "START" );
starter.addActionListener ( this );
starter.setLocation ( 10, 10 );
starter.setSize ( 130, 80 );
this.add ( starter );
pauser = new JButton ( "PAUSE" );
pauser.addActionListener ( this );
pauser.setLocation ( 150, 10 );
pauser.setSize ( 130, 80 );
this.add ( pauser );
reset = new JButton ( "RESET" );
reset.addActionListener ( this );
reset.setLocation ( 290, 10 );
reset.setSize ( 130, 80 );
this.add ( reset );
}
public void setUpValues ( )
{
timer = null;
running = paused = false;
startTime = 0;
seconds = time = 0.0;
}
public void paintComponent ( Graphics g )
{
super.paintComponent ( g );
g.setColor ( Color.white );
g.setFont ( mine );
g.drawString ( "Running: " + Format.left ( time, 0, 1 ) + " seconds", 20, 140 );
}
public void actionPerformed(ActionEvent evt)
{
String command = evt.getActionCommand();
if ( command != null )
{
if ( command.equals ( "START" ) )
{
// Record the time and start the stopwatch.
if ( paused )
{
startTime = evt.getWhen() - (long)(1000 * seconds); //Time when mouse was clicked.
paused = false;
}
else
startTime = evt.getWhen();
running = true;
if (timer == null)
{
timer = new Timer ( 100, this );
timer.start ( );
}
else
timer.restart ( );
}
else if ( command.equals ( "PAUSE" ) && running && !paused )
{
// Stop the stopwatch. Compute the elapsed time since the
// stopwatch was started and display it.
timer.stop();
long endTime = evt.getWhen();
seconds = (endTime - startTime) / 1000.0;
paused = true;
}
else if ( command.equals ( "RESET" ) )
{
timer.stop();
timer = null;
setUpValues ( );
}
}
if ( !paused )
{
if ( running )
time = (System.currentTimeMillis() - startTime) / 1000.0;
else
time = 0.0;
}
this.repaint ( );
}
}
Back to Lesson 31 Examples
Back to Java Main Page