Reputation: 897
I'm trying to make a stopwatch that constantly updates to the screen what the time is. The time object is a JLabel that should display the time elapsed. I have everything imported and set up right, but whenever the start button is clicked to activate the timer, the program freezes.
public class Timing
{
public void Timer()
{
startTime = System.currentTimeMillis();
while(isTiming == true)
{
endTime = System.currentTimeMillis();
elapsedTime = endTime - startTime;
time.setText("" + elapsedTime);
info.validate();
}
endTime = System.currentTimeMillis();
elapsedTime = endTime - startTime;
time.setText("" + elapsedTime);
info.validate();
}
}
Here's the Action Listener part:
public void actionPerformed(ActionEvent arg0)
{
if(((JButton) arg0.getSource()).getText().equals("Start"))
{
isTiming = true;
new Timing().Timer();
}
Upvotes: 2
Views: 931
Reputation: 16476
You are trying to synchronously update your label in a loop in the UI thread, the same thread which is used for applying UI updates. By doing this you are blocking the execution which results into the freeze you are describing.
To resolve this, you could use the javax.swing.Timer
to schedule the updates so that they would be run in the same UI thread, but only when needed, i.e.
timer = new javax.swing.Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
...
time.setText("" + elapsedTime);;
}
});
...
public void actionPerformed(ActionEvent arg0)
{
if(((JButton) arg0.getSource()).getText().equals("Start"))
{
isTiming = true;
timer.start();
}
}
Upvotes: 7