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.currentTi开发者_开发知识库meMillis();
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.
Maybe try using the SwingWorker
class (check it out in the javadocs) and the get()
method that comes along with it.
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);
}
}
精彩评论