本文介绍了如何更改进度条和标签的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JLabel JProgressBar 只有在方法结束时才会更改其值。

The JLabel and JProgressBar do not change their value, only when the method ends.

this.desSave.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        DownloadXml();
    }
});

private void DownloadXml() throws Exception {
    Integer a = 456;
    int value = (1000 / a) - 1;
    this.numDes.setText("0" + "/" + a);
    for (int i = 0; i < a; i++) {
        saveXml(ligas.get(i),i,path);
        this.numDes.setText(i + "/" + a); //this is a jlabel
        this.progressbar.setValue(value * i); //jprogressbar
    }
}

private void SaveXml(String xml,int a,String path) throws IOException {
}


推荐答案

您正在阻止事件派发线程,这阻止了它更新UI。您可以使用 Thread ,但Swing是单线程API,这意味着只应在事件调度线程的上下文中对UI进行更新。

You're blocking the event dispatch thread, which is preventing it from updating the UI. You could use a Thread, but Swing is a single threaded API, meaning that updates should only be made to UI from within the context of the event dispatching thread.

您可以使用 SwingWorker ,这将允许您在后台线程中执行长时间运行的进程,但是它支持安全地同步UI的更新。

You could use a SwingWorker, which will allow you to execute your long running process in a background thread, but which has support for synchronising updates to the UI safely.

连同进度 PropertyChange 支持,它变得易于管理。

Together with its progress and PropertyChange support, it becomes easy to manage, for example.

public class Worker extends SwingWorker<Object, Object> {

    @Override
    protected Object doInBackground() throws Exception {

        // The download code would go here...
        for (int index = 0; index < 1000; index++) {

            int progress = Math.round(((float)index / 1000f) * 100f);
            setProgress(progress);

            Thread.sleep(10);

        }

        // You could return the down load file if you wanted...
        return null;

    }
}

进度窗格

public class ProgressPane extends JPanel {

    private JProgressBar progressBar;

    public ProgressPane() {

        setLayout(new GridBagLayout());
        progressBar = new JProgressBar();

        add(progressBar);

    }

    public void doWork() {

        Worker worker = new Worker();
        worker.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if ("progress".equals(evt.getPropertyName())) {
                    progressBar.setValue((Integer) evt.getNewValue());
                }
            }

        });

        worker.execute();

    }

}

你可以使用发布 / 进程支持和更新EDT, PropertyChange 支持或工人的完成方法,以便在安全的情况下从EDT内获得工人的结果

You can use the publish/process support to and updates to the EDT, the PropertyChange support or the worker's done method to get the result of the worker when it's done safely, from within the EDT

这篇关于如何更改进度条和标签的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 19:02