【问题标题】:How to update a progress bar from a method inside SwingWorker如何从 SwingWorker 中的方法更新进度条
【发布时间】:2014-07-24 22:49:41
【问题描述】:

我正在尝试更新进度条,但我做不到。我的代码是这样的:

public class MyWorker extends SwingWorker<Void, Void> {

    public Void doInBackground(){
        howMany=Integer.parseInt(textField.getText());
        String result=longMethod(howMany);
        label.setText("Hello, you have "+result);
 }
}

        public class Event implements ActionListener{
    public void actionPerformed(ActionEvent e){
        label2.setText("Whatever");     
        button.setEnabled(false);
        myWorer.addPropertyChangeListener(this);
        myWorker.execute();
    }

    public void propertyChange(PropertyChangeEvent event){
        if("progress".equals(event.getPropertyName())){
           int currentPercent = (int)event.getNewValue();
            progressBar.setValue(currentPercent);
        }
    }
}

所以我不能在doInBackground 中使用setProgress,因为更新是由longMethod() 进行的,该方法包含一个大的慢循环,放置在另一个类中。我做了类似的事情,从该方法传递一个变量到包含 JFrame 的类,然后如果您单击另一个按钮,则可以查看该进度。

我不知道是否有某种方法可以使该按钮(或文本字段)每 X 秒刷新一次而无需单击它或使用方法 longMethod() 中的 setProgress

谢谢!

【问题讨论】:

    标签: java swing swingworker jprogressbar


    【解决方案1】:

    您需要某种方式让longMethod 返回进度信息。

    例如,您可以创建一个简单的interface,您可以将其传递给longMethod,当它知道时,它会更新进度...

    public interface ProgressMonitor {
        /**
         * Passes the progress of between 0-1
         */
        public void progressUpdated(double progress);
    }
    

    然后在您的doInBackground 方法中,您会将ProgressMonitor 的实例传递给longMethod

    public class MyWorker extends SwingWorker<Integer, Integer> {
        public Integer doInBackground(){
            // It would be better to have obtained this value before
            // doInBackground is called, but that's just me...
            howMany=Integer.parseInt(textField.getText());
            String result=longMethod(howMany, new ProgressMonitor() {
                public void progressUpdated(double progress) {
                    setProgress((int)(progress * 100));
                }
            });
            //label.setText("Hello, you have "+result);
            publish(result);
            return result;
        }
    
        protected void process(List<Integer> chunks) {
            label.setText("Hello, you have "+chunks.get(chunks.size() - 1));
        }
    }
    

    这基本上是observer pattern 的一个例子

    现在,如果你不能修改longMethod,那么你就没有办法更新进度,因为你无法知道longMethod在做什么......

    【讨论】:

      【解决方案2】:

      如果有办法将进度条传递给 SwingWorker,那么 SwingWorker 将拥有对该进度条的引用并能够对其进行更新。

      【讨论】:

      • 我已经可以使用 setProgress() 从 SwingWorker 更新它,问题是我想从 SwingWorker 中的 longMethod() 方法来更新它。
      猜你喜欢
      • 2020-04-29
      • 1970-01-01
      • 1970-01-01
      • 2013-10-25
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 2012-03-06
      相关资源
      最近更新 更多