Reputation: 5358
I'm trying to update my Java Swing form within a for. I tried many ways, but it wasn't working. This is what I last tried:
for(int i=0; i<10; i++) {
jTextField1.setText("" + i);
try {
Thread.sleep(500);
}
catch (InterruptedException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
Upvotes: 0
Views: 1845
Reputation: 138
You can't make your jTextField1 variable 'final' but you can use a local variable declared final and set to your jTextField1 variable as I showed below...I used many times such approach in my coding, it works...
final jTextField local_var = jTextField1;SwingUtilities.invokeLater(new Runnable() {
public void run() {
for (int i=0; i<10; i++) { local_var.setText("" + i); }});
Upvotes: 1
Reputation: 530
I suppose you are trying to update component from external thread. In general, Swing is not thread safe, for more details take a look at this. Regarding to your code, try follow this approach:
for(int i=0; i<10; i++) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
jTextField1.setText("" + i);
}
});
}
Variable jTextField1
must be declared as final
.
Upvotes: 0