Update a Label with a Swing Timer
I'm having some trouble with this piece of code.
I'm starting a timer with a random number, and I want to update a JLabel with the countdown, every second. But I haven't figured out how to do so, since the only listener the timer triggers is at the end of it (that I know).
here's the code:
int i = getTimer(maxWait);
te1 = new Timer(i, this);
label.setText(i+"");
te1.start();
...
public int getTimer(int max){
Random generator = new Random();
int i = generator.nextInt(max);
return i*1000;
}
...
public void actionPerformed(ActionEvent ev){
if(ev.getSource() == te1){
label.setText(i+"");
te1.stop();
}
}
I don't really understand your question why you are using the Random, but here are some observations:
I want to update a JLabel with the countdown, every second.
Then you need to set the Timer to fire every second. So the parameter to the Timer is 1000, not some random number.
Also, in your actionPerformed() method you stop the Timer the first time it fires. If you are doing a count down of some kind then you would only stop the Timer when the time reaches 0.
Here is a simple example of using a Timer. It just updates the time every second:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class TimerTime extends JPanel implements ActionListener
{
private JLabel timeLabel;
public TimerTime()
{
timeLabel = new JLabel( new Date().toString() );
add( timeLabel );
Timer timer = new Timer(1000, this);
timer.setInitialDelay(1);
timer.start();
}
@Override
public void actionPerformed(ActionEvent e)
{
//System.out.println(e.getSource());
timeLabel.setText( new Date().toString() );
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("TimerTime");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new TimerTime() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
If you need more help then update your question with a proper SSCCE demonstrating the problem. All questions should have a proper SSCCE, not just a few random lines of code so we can understand the context of the code.