Java Swing中的线程不起作用

时间:2013-10-04 19:29:22

标签: java multithreading swing event-dispatch-thread jprogressbar

我有一些带有for循环的简单代码。在循环的每次传递中,我必须增加JProgressBar;但是,这不起作用。见下文:

public void atualizarBarraDeProgresso(final int valorGeral, final int valorAtual) {
    Thread threadProgressoCarregamento = new Thread() {
        @Override
        public void run() {
             jProgressBarPersistindo.setValue(valorAtual);
        }
    };
    threadProgressoCarregamento.start();
}

我在下面的循环中调用方法“atualizarBarraDeProgresso”:

progressBar.setMinimum(0);
progressBar.setMaximum(qtd);
for(int i = 0; i < qtd; i++) { 
    atualizarBarraDeProgresso(qtd, i + 1);
    doSomething();
}

但我的progressBar没有任何反应。

2 个答案:

答案 0 :(得分:0)

尝试在for语句之前添加一个线程。我希望它有效

    progressBar.setMinimum(0);
    progressBar.setMaximum(qtd);

    new Thread(){
        @Override
        public void run() {
            for(int i = 0; i < qtd; i++) { 
                atualizarBarraDeProgresso(qtd, i + 1);
                doSomething();
            }
        }
    }.start();

答案 1 :(得分:0)

这应该通过SwingWorker实施轻松管​​理。当您需要“执行某些操作”但不想在执行操作时阻止GUI时,SwingWorker非常有用。当您需要在通过publish()/process()方法执行其他工作时更新GUI组件时,该类还为您提供了一个有用的API,用于与EDT进行通信。

以下实现处理工作线程上的循环,以便它不会阻止EDT(GUI线程)。对publish(Integer...)的呼叫被转发到EDT作为process(List)的呼叫,这是您要更新JProgressBar的地方,因为像所有Swing组件一样,您应该只更新EDT上的JProgressBar。

public class MySwingWorker extends SwingWorker<Void, Integer> {

    private final int qtd;
    private final JProgressBar progressBar;

    public MySwingWorker(JProgressBar progressBar, int qtd){
        this.qtd = qtd;
        this.progressBar = progressBar;
    }

    /* This method is called off the EDT so it doesn't block the GUI. */
    @Override
    protected Void doInBackground() throws Exception {
        for(int i = 0; i < qtd; i++) { 

            /* This sends the arguments to the process(List) method 
             * so they can be handled on the EDT. */
            publish(i + 1);

            /* Do your stuff. */
            doSomething();
        }
        return null;
    }

    /* This method is called on the EDT in response to a 
     * call to publish(Integer...) */
    @Override
    protected void process(List<Integer> chunks) {
        progressBar.setValue(chunks.get(chunks.size() - 1));
    }
}

你可以像这样开始

int qtd = ...;

progressBar.setMinimum(0);
progressBar.setMaximum(qtd);

SwingWorker<? ,?> worker = new MySwingWorker(progressBar, qtd);

worker.execute();