java setText in loop
Hi im trying to setText to JTextArea in loop but I want to do it, thtat in each loop every line will be seen in frame.
I have tryied with Thread.sleep(500)
, becouse I thought loop is too fast to set each line, but its开发者_开发技巧 didnt help.
Is it possible ?? to do it ? I want to do it to show to user progress with downloading files from database.
the nature of event-based singlethreaded guis makes it so that the changes are only visible once the event is fully handled (returned from the event handler)
blocking the event dispatch thread won't help (and even makes the entire app unresponsive)
you should use a timer to simulate the adding one at the time with a delay in between
final String[] lines;
for(int i=0; i<10; i++){
Timer t = new Timer(500*i,new ActionListener(){
int ind=i;
void actionPerformed(ActionEvent e){
area.setText(area.getText() + "\n ...");
}
});
t.start();
}
this creates 10 timers each adding a line after some time (increments of 500)
there's a better way to do this that reuses the timer and stops it after everything is done but it's a bit more verbose
I think JTextArea.append(text)
might be more useful.
精彩评论