tags:

views:

78

answers:

2

for my application I have to build a little customized time ticker which ticks over after whatever delay I tell it to and writes the new value in my textArea. The problem is that the ticker is running fully until the termination time and then printing all the values. How can I make the text area change while the code is running.

while(tick<terminationTime){
    if ((System.currentTimeMillis()) > (msNow + delay)){
        msNow = System.currentTimeMillis();
        tick = tick + 1;
        currentTime.setText(""+tick);
        sourceTextArea.append(""+tick+"  " +  System.currentTimeMillis() +" \n");
    }
}

currentTime and sourceTextArea are both text areas and both are getting updated after the while loop ends.

+1  A: 

Maybe try using the SwingWorker class (check it out in the javadocs) and the get() method that comes along with it.

chama
+1  A: 

Here is an example that works with 2 threads.

Here is the update thread.

public class updateThread extends Thread
{
textAreaTest aa;
Integer i;
public updateThread(textAreaTest abc)
   {
            aa = abc;
            i = 0;
   }

@Override
   public void run()
   {
        while(true)
            {
                try
                  {
                      sleep(1000);
                  }
              catch (InterruptedException e)
                  {
                      //e.printStackTrace();
                  }
              aa.setText(i.toString());
              i++;
            }
   }

}

And here is the Jpanel

import java.awt.Container;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class textAreaTest extends javax.swing.JFrame
{
JTextArea area = new JTextArea();

public static void main(String[] args)
    {
        new textAreaTest();
    }

public textAreaTest()
    {
        updateThread thread = new updateThread(this);
        JPanel panel = new JPanel();
        panel.add(area);
        this.setSize(100, 100);
        Container c = this.getContentPane();
        c.add(area);
        this.pack();
        this.setVisible(true);
        thread.start();
    }

public void setText(String text)
    {
        area.setText(text);
    }
}
Milhous
good ideas here, but don't use e.printStackTrace() on an InterruptedException which can happen under reasonable circumstances.
Jason S
Jason, i was just showing that this works. You are probably correct..
Milhous