java swingworker线程更新主桂

时间:2013-06-05 10:52:04

标签: java swing swingworker

嗨id想知道从swingworkerthread向jtextarea添加文本的最佳方法,我创建了另一个jtton调用Threadsclass()的类.execute(); 并且线程与此代码并行运行

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

}

现在我喜欢做的是将x的值添加到主gui的文本区域,任何想法都非常感激。

2 个答案:

答案 0 :(得分:8)

JavaDocs

有一个很好的例子
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 + "\n");
        }
    }
}

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

查看publishprocess

潜在的意图是您需要仅在事件调度线程内更新UI,方法是通过publish方法将要更新的数据传递给用户界面,SwingWorker将调用{在EDT的背景下为您提供{1}}

答案 1 :(得分:4)