Java Swing 并发显示 JTextArea [英] Java Swing Concurrency display JTextArea
问题描述
我需要执行/显示从 Arraylist 到 JTextArea 的一系列事件,但是,每个事件在不同的时间执行.以下是我的目标的一个简单示例:
I need to execute/display a series of events from a Arraylist to a JTextArea, however, each Event gets execute with different time. Following is a quick example of my goal:
public void start(ActionEvent e)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
jTextArea.append("Test" + "\n");
try
{
Thread.sleep(3000);
} catch (InterruptedException e1)
{
e1.printStackTrace();
}
jTextArea.append("Test1" + "\n");
}
});
}
所以现在,在整个执行完成后,Test"和Test1"显示在 JTextArea 上.如何先显示Test",然后在 3 秒后显示Test1"
So right now, "Test" and "Test1" display on JTextArea after whole execution is completed. How do I make "Test" display first, then 3 secs later, display "Test1"
先谢谢大家
推荐答案
invokeLater
安排 runnable 在事件调度线程上运行.你不应该在里面睡觉,否则你会饿死调度线程.尝试使用单独的工作线程:
invokeLater
schedules the runnable to run on the Event Dispatch Thread. You shouldn't sleep within it or you will starve the dispatch thread. Try using a separate worker thread instead:
Thread worker = new Thread(new Runnable(){
public void run(){
jTextArea.append("Test" + "\n");
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
jTextArea.append("Test1" + "\n");
}
});
worker.start();
这篇关于Java Swing 并发显示 JTextArea的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!