从新线程更新 JProgressBar [英] Update JProgressBar from new Thread

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

问题描述

如何从另一个线程更新 JProgressBar.setValue(int)?我的次要目标是在尽可能少的课程中完成.

How can I update the JProgressBar.setValue(int) from another thread? My secondary goal is do it in the least amount of classes possible.

这是我现在拥有的代码:

Here is the code I have right now:

// Part of the main class....
pp.addActionListener(
        new ActionListener(){
            public void actionPerformed(ActionEvent event){
                new Thread(new Task(sd.getValue())).start(); 
            }
        });

public class Task implements Runnable {
    int val;
    public Task(int value){
        this.val = value;
    }

    @Override
    public void run() {
        for (int i = 0; i <= value; i++){ // Progressively increment variable i 
            pbar.setValue(i); // Set value 
            pbar.repaint(); // Refresh graphics 
            try{Thread.sleep(50);} // Sleep 50 milliseconds 
            catch (InterruptedException err){} 
        } 
    }
}

pp 是一个 JButton,当 JButton 被点击时启动新线程.

pp is a JButton and starts the new thread when the JButton is clicked.

pbar 是 Main 类中的 JProgressBar 对象.

pbar is the JProgressBar object from the Main class.

如何更新它的值?(进度)

How can I update its value?(progress)

上面run()中的代码看不到pbar.

The code above in run() cannot see the pbar.

推荐答案

始终遵守 Swing 的规则

Always obey swing's rule

一旦实现了 Swing 组件,所有可能影响或依赖于该组件状态的代码都应该在事件分派线程中执行.

你可以做的是创建一个观察者来更新你的进度条——比如- 在这种情况下,您希望通过单击按钮显示正在加载的数据的进度.DemoHelper 类实现 Observable 并在加载特定百分比的数据时向所有观察者发送更新.进度条通过 public void update(Observable o, Object arg) {

What you can do is to create an observer that will update your progress bar -such as - in this instance you want to show progress of data being loaded on click of a button. DemoHelper class implements Observable and sends updates to all observers on when certain percent of data is loaded. Progress bar is updated via public void update(Observable o, Object arg) {

class PopulateAction implements ActionListener, Observer {

    JTable tableToRefresh;
    JProgressBar progressBar;
    JButton sourceButton;
    DemoHelper helper;
    public PopulateAction(JTable tableToRefresh, JProgressBar progressBarToUpdate) {
        this.tableToRefresh = tableToRefresh;
        this.progressBar = progressBarToUpdate;
    }

    public void actionPerformed(ActionEvent e) {
        helper = DemoHelper.getDemoHelper();
        helper.addObserver(this);
        sourceButton = ((JButton) e.getSource());
        sourceButton.setEnabled(false);
        helper.insertData();
    }

    public void update(Observable o, Object arg) {
        progressBar.setValue(helper.getPercentage());
    }
}

无耻的插件:这是来自 来自我的演示项目的源请随意浏览以了解更多详情.

Shameless plug: this is from source from my demo project Feel free to browse for more details.

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

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