java swingworker线程更新主桂 [英] java swingworker thread to update main Gui

查看:268
本文介绍了java swingworker线程更新主桂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

}

现在我喜欢做的是将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.

推荐答案

有一个很好的例子来自 JavaDocs

There is an excellent example from the 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

看看发布进程

潜在的意图是你需要仅通过事件调度线程更新UI,方法是将你想要更新的数据通过发布传递给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

这篇关于java swingworker线程更新主桂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆