Reputation: 27
I'm fairly new to Java and would like to know where I'm going wrong with this code
for(int i=0; i<10; i++) {
textArea.setText("\n***Iterate***\n");
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
}
}
what I expect for this to do is for every iteration, it should have an interval of a second. But what happens is that when it runs, it sleeps for 10 seconds, and then the for loop runs as how it would without the thread.sleep().
Upvotes: 0
Views: 32
Reputation: 11020
If this is being done on the EDT (which you should because you're updating a Swing component), then it's because you're blocking the EDT for 10 seconds.
Consider a Swing timer instead. https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html
class MyActionListener implements ActionListner {
Timer mytimer;
int count;
public void actionPerformed(ActionEvent evt) {
textArea.setText("\n***Iterate***\n");
if( ++count > 10 ) mytimer.stop();
}
};
MyActionListener task = new MyActionListener();
Timer timer = new Timer(1000, task )
task.mytimer = timer;
timer.setRepeats( true );
timer.start();
Code is untested.
Upvotes: 1