用于更新主 Gui 的 java swingworker 线程 [英] java swingworker thread to update main Gui
问题描述
我想知道从 Swingworkerthread 向 jtextarea 添加文本的最佳方法是什么,我创建了另一个类,jbutton 通过 Threadsclass().execute(); 调用该类;并且线程与此代码并行运行
hi id like to know whats the best way to add text to a jtextarea from a swingworkerthread, ive created another class which a jbutton calls by Threadsclass().execute(); and the thread runs in parallel fine with this code
public class Threadsclass extends SwingWorker<Object, Object> {
@Override
protected Object doInBackground() throws Exception {
for(int x = 0; x< 10;x++)
try {
System.out.println("sleep number :"+ x);
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(eftcespbillpaymentsThreads.class.getName()).log(Level.SEVERE, null, ex);
}
throw new UnsupportedOperationException("Not supported yet.");
}
}
现在 id 喜欢做的是将 x 的值添加到主 gui 上的文本区域,非常感谢任何想法.
now what id like to do is add the value of x to the text area on the main gui, any ideas much appreciated.
推荐答案
class PrimeNumbersTask extends
SwingWorker<List<Integer>, Integer> {
PrimeNumbersTask(JTextArea textArea, int numbersToFind) {
//initialize
}
@Override
public List<Integer> doInBackground() {
List<Integer> numbers = new ArrayList<Integer>(25);
while (!enough && !isCancelled()) {
number = nextPrimeNumber();
numbers.add(number);
publish(number);
setProgress(100 * numbers.size() / numbersToFind);
}
return numbers;
}
@Override
protected void process(List<Integer> chunks) {
for (int number : chunks) {
textArea.append(number + "
");
}
}
}
JTextArea textArea = new JTextArea();
final JProgressBar progressBar = new JProgressBar(0, 100);
PrimeNumbersTask task = new PrimeNumbersTask(textArea, N);
task.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equals(evt.getPropertyName())) {
progressBar.setValue((Integer)evt.getNewValue());
}
}
});
task.execute();
System.out.println(task.get()); //prints all prime numbers we have got
基本意图是您只需要在事件调度线程内更新 UI,通过 publish
方法将要更新的数据传递到 UI,SwingWorker
将在 EDT 的上下文中为您调用 process
The underlying intention is that you need to update the UI from only within the Event Dispatching Thread, by passing the data you want to updated to the UI via the publish
method, SwingWorker
will call process
for you within the context of the EDT
这篇关于用于更新主 Gui 的 java swingworker 线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!