0

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);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Marin Bînzari
  • 5,208
  • 2
  • 26
  • 43
  • 4
    Don't block the EDT (Event Dispatch Thread) - the GUI will 'freeze' when that happens. Instead of calling `Thread.sleep(n)` implement a Swing `Timer` for repeating tasks or a `SwingWorker` for long running tasks. See [Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/) for more details. – Andrew Thompson May 06 '13 at 17:35
  • possible duplicate of [how to update a jLabel every time with a while loop with a delay](http://stackoverflow.com/questions/7251675/how-to-update-a-jlabel-every-time-with-a-while-loop-with-a-delay) (and of dozens of other similar questions) – JB Nizet May 06 '13 at 17:39
  • Thanks for replies. I'll see what I can do with Timer. The problem is that I make Math calculations in a loop, so I don't know how to implement this with Timer. – Marin Bînzari May 06 '13 at 17:46
  • @SpartakusMd Then, SwingWorker is your friend. Check out [this answer](http://stackoverflow.com/questions/16010990/changing-jtextfields-text-while-iterating-or-inside-a-loop/16011226#16011226) – Guillaume Polet May 06 '13 at 18:16

2 Answers2

1

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); }});

Ali VELI
  • 138
  • 1
  • 7
0

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.

Eugene
  • 520
  • 3
  • 8
  • Just tried that. If I declare `jTextField1` as `final` then initialisation of the field fails. Can't assign value to final variables. – Marin Bînzari May 06 '13 at 17:59
  • You can create class which implements Runnable and takes jTextField1 as parameter. – Eugene May 06 '13 at 18:31