Can someone provide me an example of a Swing Timer stopwatch GUI in Java using a constantly-updating JLabel? I am not familiar with using @Override, so please don't suggest code with that in it unless it is absolutely necessary (I've done other Swing Timers, such as a system clock, without it).
Thanks!
EDIT: As per @VGR's request, here's the code I have for my basic clock that uses a Swing Timer:
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.FlowLayout;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
public class basic_clock extends JFrame
{
JLabel date, time;
public basic_clock()
{
super("clock");
ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
Calendar current = Calendar.getInstance();
current.setTime(new Date());
date.setText((current.get(Calendar.MONTH) + 1) +"/" +current.get(Calendar.DATE) +"/" +current.get(Calendar.YEAR));
String timeStr = String.format("%d:%02d:%02d", current.get(Calendar.HOUR), current.get(Calendar.MINUTE), current.get(Calendar.SECOND));
time.setText(timeStr);
}
};
date = new JLabel();
time = new JLabel();
setLayout(new FlowLayout());
setSize(310,190);
setResizable(false);
setVisible(true);
add(date);
add(time);
date.setFont(new Font("Arial", Font.BOLD, 64));
time.setFont(new Font("Arial", Font.BOLD, 64));
javax.swing.Timer timer = new javax.swing.Timer(500, listener);
timer.setInitialDelay(0);
timer.start();
}
public static void main(String args[])
{
basic_clock c = new basic_clock();
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Obviously I need something different than the Calendar object since I want to keep track of minutes and seconds to the nearest 1/100th of a second instead of date/month/year/hour/minute/second.
Then you have a bigger problem. How do you expect any of us to provide you with an example you can understand?
A stop watch is conceptually pretty simple, it's simply the amount of time that has passed since it was started. Problems arise when you want to be able to pause the timer, as you need to take into account the amount of time the timer has been running plus the time since it was last started/resumed.
Another issue is, most timers only guarantee a minimum amount of time, so they are imprecise. This means you can't just keep adding the amount of the timer's delay to some variable, you'll eventually end up with a drifting value (inaccurate)
This is a very simple example, all it does is provides a start and stop button. Each time the stop watch is started, it starts from
0
again.Adding a pause feature isn't hard, it would simply require one additional variable, but I'll leave that up to you to figure out.