The idea of my program is to select one name from a list that saved before in other JFrame. I\'d like to print in the label all names one after the other with small delay betwee
Don't use a loop or Thread.sleep
. Just use a javax.swing.Timer
. The following will cause 30 iterations occurring every 1000 milliseconds. You can adjust the code in the actionPerformed
accordingly to what you wish to happen every so many milliseconds.
int count = 0;
...
Timer timer = new Timer(1000, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
if (count == 30) {
((Timer)e.getSource()).stop();
} else {
int rand = (int) (Math.random()* RandomNames.size);
stars.setText(RandomNames.list.get(rand));
count++;
}
}
});
timer.start();
If you want you can just set up the Timer
in the constructor, and start()
it in the actionPerformed
of another button's listener.
See more at How to use Swing Timers