Restarting a method with ActionListener - java

Im making a timer for a game ive created, but Im having a hard time restarting my timer method. It pauses the timer for about a second then continues to count, ex: if the timer is on 4, if the reset button is hit the timer will pause at 4 for a second then resume to 5, 6, etc. Anyway to fix this?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyTimer extends Panel {
private JLabel timeDisplay;
private JButton resetButton;
private JButton startButton;
private JButton stopButton;
Timer timer;
public MyTimer(){
MyTimer timer;
startButton = new JButton("Start Timer");
stopButton = new JButton("Stop Timer");
timeDisplay = new JLabel("...Waiting...");
resetButton = new JButton("Reset Timer");
this.add(resetButton);
this.add(startButton);
this.add(stopButton);
this.add(timeDisplay);
event e = new event();
startButton.addActionListener(e);
event1 c = new event1();
stopButton.addActionListener(c);
event2 d = new event2();
resetButton.addActionListener(d);
}
public class event implements ActionListener{
public void actionPerformed(ActionEvent e){
int count = 0;
timeDisplay.setText("Elapsed Time in Seconds: " + count);
TimeClass tc = new TimeClass(count);
timer = new Timer(1000, tc);
timer.start();
}
}
public class TimeClass implements ActionListener{
int counter;
public TimeClass(int counter){
this.counter = counter;
}
public void actionPerformed(ActionEvent e){
counter++;
timeDisplay.setText("Elapsed Time in Seconds: " + counter);
}
}
class event1 implements ActionListener{
public void actionPerformed (ActionEvent c){
timer.stop();
}
}
class event2 implements ActionListener{
public void actionPerformed (ActionEvent d){
timer.restart();
}
}
}

create a global counter in MyTimer class
static volatile int counter;
....
class event implements ActionListener {
public void actionPerformed(ActionEvent e) {
// handle the condition if start button is clicked
// more than once continuously.
if (timer == null) {
TimeClass tc = new TimeClass();
timer = new Timer(1000, tc);
}
timer.start();
}
}
class TimeClass implements ActionListener {
public void actionPerformed(ActionEvent e) {
counter++;
timeDisplay.setText("Elapsed Time in Seconds: " + counter);
}
}
class event1 implements ActionListener {
public void actionPerformed(ActionEvent c) {
// handle the condition if stop is clicked before starting the timer
if (timer != null) {
timer.stop();
}
}
}
class event2 implements ActionListener {
public void actionPerformed(ActionEvent d) {
// reset the counter
counter = 0;
// handle the condition if reset is clicked before starting the timer
if (timer != null) {
timer.restart();
}
}
}

Related

How to make a pause-able count up timer in Java?

I'm trying to make a timer that will count up from 00h:00m:00s, with the ability to pause and restart the count from its current time.
Heres the solution I currently have: It will always restart the timer from 0 instead of continuing where it left off. Also, for another inexplicable reason, the hours always display as 07 instead of 00. Does anyone know how I could fix these issues, to have it start counting up from its previous value, and display the correct amount of hours elapsed?
private final SimpleDateFormat date = new SimpleDateFormat("KK:mm:ss");
private long startTime = 0;
private final ClockListener clock = new ClockListener();
private final Timer normalTimer = new Timer(53, clock);
startTimerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(startTime == 0) {
startTime = System.currentTimeMillis();
}
else {
startTime += (System.currentTimeMillis() - startTime);
}
normalTimer.start();
}
});
stopTimerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
normalTimer.stop();
}
});
private void updateClock(){
Date elapsed = new Date(System.currentTimeMillis() - startTime);
timerText.setText(date.format(elapsed));
}
private class ClockListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
updateClock();
}
}
Introduction
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section.
Your code wasn't runnable, so I created the following GUI.
When you press the "Start" button, the timer starts counting. 37 seconds.
2 minutes, 7 seconds.
1 hour, 6 minutes, 11 seconds.
Pressing the "Pause button pauses the count. Pressing the "Restart" button resumes the count. You can pause and resume the count as many times as you want.
Pressing the "Stop" button stops the counter. You can press the "Reset" button to reset the counter before starting again.
Explanation
When creating a Swing application, using the model-view-controller (MVC) pattern helps to separate your concerns and allows you to focus on one part of the application at a time.
Creating the application model made creating the GUI much easier. The application model is made up of one or more plain Java getter/setter classes.
The CountupTimerModel class keeps long fields to hold the duration in milliseconds and the previous duration. This way, I don't have to pause and restart the Swing Timer.
The duration is the difference between the current time and the start time. I use the System.currentTimeMillis() method to calculate the duration.
The GUI is fairly straightforward.
I made the JButton ActionListeners lambdas. I made the TimerListener a separate class to move the code out of that particular lambda.
Code
Here's the complete runnable code. I made the additional classes inner classes so I could post the code as one block.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class CountupTimerGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new CountupTimerGUI());
}
private final CountupTimerModel model;
private JButton resetButton, pauseButton, stopButton;
private JLabel timerLabel;
public CountupTimerGUI() {
this.model = new CountupTimerModel();
}
#Override
public void run() {
JFrame frame = new JFrame("Countup Timer GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createDisplayPanel(), BorderLayout.NORTH);
frame.add(createButtonPanel(), BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createDisplayPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font font = panel.getFont().deriveFont(Font.BOLD, 48f);
timerLabel = new JLabel(model.getFormattedDuration());
timerLabel.setFont(font);
panel.add(timerLabel);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font font = panel.getFont().deriveFont(Font.PLAIN, 16f);
resetButton = new JButton("Reset");
resetButton.setFont(font);
panel.add(resetButton);
resetButton.addActionListener(event -> {
model.resetDuration();
timerLabel.setText(model.getFormattedDuration());
});
pauseButton = new JButton("Restart");
pauseButton.setFont(font);
panel.add(pauseButton);
pauseButton.addActionListener(event -> {
String text = pauseButton.getText();
if (text.equals("Pause")) {
model.pauseTimer();
pauseButton.setText("Restart");
} else {
model.startTimer();
pauseButton.setText("Pause");
}
});
Timer timer = new Timer(200,
new CountupListener(CountupTimerGUI.this, model));
stopButton = new JButton("Start");
stopButton.setFont(font);
panel.add(stopButton);
stopButton.addActionListener(event -> {
String text = stopButton.getText();
if (text.equals("Start")) {
model.resetDuration();
model.startTimer();
timer.start();
resetButton.setEnabled(false);
stopButton.setText("Stop");
} else {
model.stopTimer();
timer.stop();
resetButton.setEnabled(true);
stopButton.setText("Start");
}
});
Dimension d = getLargestJButton(resetButton, pauseButton, stopButton);
resetButton.setPreferredSize(d);
pauseButton.setPreferredSize(d);
stopButton.setPreferredSize(d);
pauseButton.setText("Pause");
return panel;
}
private Dimension getLargestJButton(JButton... buttons) {
Dimension largestDimension = new Dimension(0, 0);
for (JButton button : buttons) {
Dimension d = button.getPreferredSize();
largestDimension.width = Math.max(largestDimension.width, d.width);
largestDimension.height = Math.max(largestDimension.height,
d.height);
}
largestDimension.width += 10;
return largestDimension;
}
public JButton getResetButton() {
return resetButton;
}
public JButton getPauseButton() {
return pauseButton;
}
public JButton getStopButton() {
return stopButton;
}
public JLabel getTimerLabel() {
return timerLabel;
}
public class CountupListener implements ActionListener {
private final CountupTimerGUI view;
private final CountupTimerModel model;
public CountupListener(CountupTimerGUI view, CountupTimerModel model) {
this.view = view;
this.model = model;
}
#Override
public void actionPerformed(ActionEvent event) {
model.setDuration();
view.getTimerLabel().setText(model.getFormattedDuration());
}
}
public class CountupTimerModel {
private boolean isRunning;
private long duration, previousDuration, startTime;
public CountupTimerModel() {
resetDuration();
}
public void resetDuration() {
this.duration = 0L;
this.previousDuration = 0L;
this.isRunning = true;
}
public void startTimer() {
this.startTime = System.currentTimeMillis();
this.isRunning = true;
}
public void pauseTimer() {
setDuration();
this.previousDuration = duration;
this.isRunning = false;
}
public void stopTimer() {
setDuration();
this.isRunning = false;
}
public void setDuration() {
if (isRunning) {
this.duration = System.currentTimeMillis() - startTime
+ previousDuration;
}
}
public String getFormattedDuration() {
int seconds = (int) ((duration + 500L) / 1000L);
int minutes = seconds / 60;
int hours = minutes / 60;
StringBuilder builder = new StringBuilder();
if (hours > 0) {
builder.append(hours);
builder.append(":");
}
minutes %= 60;
if (hours > 0) {
builder.append(String.format("%02d", minutes));
builder.append(":");
} else if (minutes > 0) {
builder.append(minutes);
builder.append(":");
}
seconds %= 60;
if (hours > 0 || minutes > 0) {
builder.append(String.format("%02d", seconds));
} else {
builder.append(seconds);
}
return builder.toString();
}
}
}

How to put timer into a GUI?

I have a GUI with a form for people to fill up and I would like to put a countdown timer at the top right hand corner of the page
Heres the method for the timer to get the remaining time. Say my form class is FillForm and the timer method is found in Timer.
How do I put a dynamic (constantly updating) timer inside of the GUI?
public String getRemainingTime() {
int hours = (int)((this.remainingTime/3600000) % 60);
int minutes = (int)((this.remainingTime/60000) % 60);
int seconds = (int)(((this.remainingTime)/1000) % 60);
return(format.format(hours) + ":" + format.format(minutes)+
":" + format.format(seconds));
}
GUI is built using NetBeans GUI builder.
Try This :
import javax.swing.Timer;
Timer timer=new Timer(1000,new ActionListener(){
public void actionPerformed(ActionEvent e)
{
//code here
}
});
timer.start();
//timer.stop()
Every one Seconds Timer Execute.
Try This Demo :
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
class Counter {
private static int cnt;
static JFrame f;
public static void main(String args[]) {
f=new JFrame();
f.setSize(100,100);
f.setVisible(true);
ActionListener actListner = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
cnt += 1;
if(cnt%2==0)
{
f.setVisible(true);
}
else
{
f.setVisible(false);
}
}
};
Timer timer = new Timer(500, actListner);
timer.start();
}
}
You should abstract your timer into a UI component. JLabel seems the most suited as it is a text that you want to display.
public class TimerLabel extends JLabel {
// Add in your code for 'format' and 'remainingTime'.
// Note that the first time that 'getText' is called, it's called from the constructor
// if the superclass, so your own class is not fully initialized at this point.
// Hence the 'if (format != null)' check
public TimerLabel() {
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
repaint();
}
});
timer.start();
}
public String getRemainingTime() {
int hours = (int) ((this.remainingTime / 3600000) % 60);
int minutes = (int) ((this.remainingTime / 60000) % 60);
int seconds = (int) (((this.remainingTime) / 1000) % 60);
return (format.format(hours) + ":" + format.format(minutes) + ":" + format.format(seconds));
}
#Override
public String getText() {
if (format != null) {
return getRemainingTime();
} else {
return "";
}
}
"Could i add this into a Swing.JPanel or something?"
Just put it in the constructor of your form class. Declare the Timer timer; as a class member and not locally scoped so that you can use the start() method like in a button's actionPerformed. Something like
import javax.swing.Timer;
public class GUI extends JFrame {
public Timer timer = null;
public GUI() {
timer = new Timer (500, new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (timerGetsToZero) {
((Timer)e.getSource()).stop();
} else {
timeLabel.setText(getRemainingTime());
}
}
});
}
private void startButtonActionPerformed(ActionEvent e) {
timer.start();
}
}

creating slideshow in java swing

I am trying to create a slideshow with Java Swing.
I began with implementing a class PicturePanel
public class PicturePanel extends JPanel {
private int counter = 0;
private ImageIcon[] images = new ImageIcon[10];
private JLabel label;
public PicturePanel()
{
for(int i = 0 ; i <images.length;i++)
{
images[counter] = new ImageIcon("check.png");
label = new JLabel();
add(label);
Timer timer = new Timer(100, new TimerListener());
}
}
private class TimerListener implements ActionListener {
public TimerListener() {
}
#Override
public void actionPerformed(ActionEvent ae) {
counter++;
//counter% =images.length;
label.setIcon(images[counter]);
}
}
}
Then I am calling this class in my Jframe through this code :
panProfil= new PicturePanel();
panProfil is a Jpanel in my form
When I run my project, I don't get any errors, but there is nothing in my form. Can someone point me in the right direction?
So you haven't started your Timer that's the problem (as #ItachiUchiha pointed out). But another thing you need to do is know when to stop() the Timer or else it will keep running
You want to start() it in the constructor after you create the Timer. In you ActionListener, to stop it, you'll want to do something like this.
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
if (counter == images.length) {
((Timer)e.getSource()).stop();
} else {
label.setIcon(images[counter]);
counter++;
}
}
}
If you want to access the Timer from your main GUI class, so you can control it, you want to have a getter for it, and declare it globally
public class PicturePanel extends JPanel {
private Timer timer = null;
public PicturePanel() {
timer = new Timer(1000, new TimerListener());
}
public Timer getTimer() {
return timer;
}
}
Then you can start and stop it from your main GUI class
DrawPanel panel = new DrawPanel();
Timer timer = panel.getTimer();
Also, I don't see the point of create a JLabel every iteration and adding it to the JPanel. You only need one.
public class Project2 {
int c=0;
public static void main(String arg[]) throws InterruptedException {
JFrame login = new JFrame("Login");
// creating a new frame
login.setSize(700, 500);
JPanel addPanel = new JPanel();
JLabel pic = new JLabel();
Project2 p2= new Project2();
String[] list = {"C:\\Users\\divyatapadia\\Desktop\\pic1.jpg", "C:\\Users\\divyatapadia\\Desktop\\benefit.PNG" , "C:\\Users\\divyatapadia\\Desktop\\pic2.jpg"};
pic.setBounds(40, 30, 500, 300);
JButton log = new JButton("SHOW");ImageIcon[] img = new ImageIcon[3];
for(int time = 0;time<3;time++) {
img[time]= new ImageIcon(list[time]);
}
addPanel.add(pic);
addPanel.add(log);
login.add(addPanel);
login.setVisible(true);
try {
log.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Timer t ;
t= new Timer(1000,new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(p2.c<3) {
pic.setIcon(img[p2.c]);
p2.c++;
}}
});
t.start();
}
}
);
}catch(Exception ex)
{
System.out.println(ex.toString());
}
}
}

Button ActionListener

Ok, so I made a simple program that adds the value to counter each time a button is clicked.
Now, I would like to add "Auto" button feature to increase the value of the counter when the "Auto" button is clicked. I'm having problems with it because it won't render each counter value on the screen, instead the value updates when the loop is done.. Here is my code:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.TimeUnit;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Gui extends JFrame{
private static final long serialVersionUID = 1L;
private JButton uselesButton;
private JButton autoButton;
private FlowLayout layout;
private long counter = 0;
public Gui() {
super("Button");
layout = new FlowLayout(FlowLayout.CENTER);
this.setLayout(layout);
uselesButton = new JButton(String.format("Pressed %d times", counter));
add(uselesButton);
uselesButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
counter++;
uselesButton.setText(String.format("Pressed %d times", counter));
}
});
autoButton = new JButton("Auto");
add(autoButton);
autoButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(long i =0; i < 99999999;i++) {
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e1) {
System.out.println("ERROR");
}
counter = i;
uselesButton.setText(String.format("Pressed %d times", counter));
}
}
});
}
}
Keep in mind that I'm a beginner... All help appreciated :)
Take a look at the tutorial about How to Use Swing Timer and then look at my solution:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Gui extends JFrame {
private static final long serialVersionUID = 1L;
private JButton uselesButton;
private JButton autoButton;
private FlowLayout layout;
private long counter = 0;
private javax.swing.Timer timer;
public Gui() {
super("Button");
layout = new FlowLayout(FlowLayout.CENTER);
setLayout(layout);
setDefaultCloseOperation(3);
setSize(300, 300);
setLocationRelativeTo(null);
//initialing swing timer
timer = new javax.swing.Timer(100, getButtonAction());
autoButton = new JButton("Auto");
add(autoButton);
autoButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (!timer.isRunning()) {
timer.start();
} else {
timer.stop();
}
}
});
}
private ActionListener getButtonAction() {
ActionListener action = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
autoButton.setText(String.format("Pressed %d times", ++counter));
if (counter > 1000) {
timer.stop();
}
}
};
return action;
}
public static void main(String... args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Gui().setVisible(true);
}
});
}
}
your code block the GUI thread (EDT) when enter inside this loop (GUI will hang, the button will not update until you finish), so you should add your code inside another worker thread:
autoButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new Thread(new Runnable() {
#Override
public void run() {
for(long i =0; i < 99999999;i++) {
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e1) {
System.out.println("ERROR");
}
counter = i;
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
uselesButton.setText(String.format("Pressed %d times", counter));
}
});
}
}
}).start();
}
});
the problem here is that the system is in the loop, so it can't paint the changes.
in order to do that you need to open a new thread. the new thread will do the loop, and the main thread will repaint the form.
one more thing, you shouldn't do sleep on the main thread. you can use a timer that will tick every 10 millisecond instead of sleep(10)
here is an example

Java clock isn't counting in Swing

I am trying to make a stopwatch using swing, but it is not working. Here is my code. The Jlabel clock is always displaying -1, which should only happen if it is stopped. Am I using the invokelater properly?
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class sidePanel extends JApplet implements ActionListener{
JPanel pane;
JLabel clock;
JButton toggle;
Timer timer;
StopWatch stopWatch;
public void init()
{
pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
clock = new JLabel("00:00");
toggle = new JButton("Start/Stop");
toggle.addActionListener(this);
pane.add(clock);
pane.add(toggle);
timer = new Timer(500, this);
timer.setRepeats(true);
stopWatch = new StopWatch();
add(pane);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == toggle)
{
if(timer.isRunning())
{
stopWatch.endTime = System.currentTimeMillis();
timer.stop();
}
else
{
stopWatch.startTime = System.currentTimeMillis();
timer.start();
}
}
if(e.getSource() == timer)
{
long time = stopWatch.getElapsedTime();
sidePanel.this.clock.setText(String.valueOf(time));
}
}
private class StopWatch{
private long startTime =0;
private long endTime =0;
public boolean isRunning = false;
public void start(){
startTime = System.currentTimeMillis();
isRunning = true;
}
public void end(){
endTime = System.currentTimeMillis();
isRunning = false;
}
public long getElapsedTime()
{
long currentTime = System.currentTimeMillis();
if(isRunning)
return (currentTime - startTime)/1000;
else
return -1;
}
}
}
Working code
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class sidePanel extends JApplet implements ActionListener{
JPanel pane;
JLabel clock;
JButton toggle;
Timer timer;
//StopWatch stopWatch;
boolean pressed = false;
long startTime =0;
long endTime =0;
public void init()
{
pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
clock = new JLabel("00:00");
toggle = new JButton("Start/Stop");
toggle.addActionListener(this);
pane.add(clock);
pane.add(toggle);
timer = new Timer(500, this);
timer.setRepeats(true);
//stopWatch = new StopWatch();
add(pane);
}
long cur;
long end;
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == toggle)
{
if(!pressed)
{
timer.start();
startTime = System.currentTimeMillis();
pressed = true;
}
else
{
timer.stop();
pressed = false;
}
}
if(timer.isRunning())
{
endTime = System.currentTimeMillis();
clock.setText(String.valueOf((endTime-startTime)/1000));
}
}
}
Your StopWatch class run once and then terminates...
public void run() {
// Start here
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run() {
long time = getElapsedTime();
sidePanel.this.clock.setText(String.valueOf(time));
}
});
// End here...
}
A thread will terminate when it exists it's run method, in this case, your StopWatch's run method.
What you need to do to is maintain a loop until the isRunning becomes false
public void run() {
while (isRunning) {
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run() {
long time = getElapsedTime();
sidePanel.this.clock.setText(String.valueOf(time));
}
});
// Because we really don't want to bombboard the Event dispatching thread
// With lots of updates, which probably won't get rendered any way,
// We put in a small delay...
// This day represents "about" a second accuracy...
try {
Thread.sleep(500);
} catch (Exception exp) {
}
}
}
It would much simpler to use a javax.swing.Timer though...
private Timer timer;
public void init()
{
pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
clock = new JLabel("00:00");
toggle = new JButton("Start/Stop");
toggle.addActionListener(this);
pane.add(clock);
pane.add(toggle);
timer = new Timer(500, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
long time = getElapsedTime();
sidePanel.this.clock.setText(String.valueOf(time));
}
});
timer.setRepeats(true);
add(pane);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == toggle)
{
if(timer.isRunning())
{
endTime = System.currentTimeMillis();
timer.stop();
}
else
{
startTime = System.currentTimeMillis();
timer.start();
}
}
}
You can then strip out the functionality from you StopWatch (ie the getElapsedTime())

Categories