当再次调用线程时,Java线程更新jProgressBar不会更新

时间:2013-09-10 14:35:49

标签: java multithreading swing jprogressbar

我有两个主题。一个是从我的BulkProcessor类运行业务逻辑,它更新BulkProcessor.getPercentComplete()变量:

public void run(){
   new SwingWorker<Void,Void>() {
      protected Void doInBackground() throws Exception {
         BulkProcessor.main(jTextField0.getText(), jTextField1.getText());
         return null;
      };
   }.execute();
}

我的另一个主题是更新我的BulkGUI类中的jProgressBar值:

public void update(){
   jProgressBar0.setStringPainted(true);
   jProgressBar0.repaint();
   new SwingWorker<Void,Integer>() {
   protected Void doInBackground() throws Exception {
      do
      {
          percentComplete = BulkProcessor.getPercentComplete();
          publish(percentComplete);
          Thread.sleep(100);
      } while(percentComplete < 100);
      return null;
      } 
      @Override
      protected
      void process(List<Integer> progress)
      {
          jProgressBar0.setValue(progress.get(0));
      }
}.execute();
}

单击Process按钮时调用两个线程:

private void jButton0ActionActionPerformed(ActionEvent event) {
run();
update();
}

第一次运行此操作完全符合预期。但是,再次选择“处理”按钮对jProgressBar没有影响。更新线程中的局部变量percentComplete保持为100,并且不会像第一次运行时那样更新。我测试了BulkProcessor类中的percentComplete变量,这个变量确实按预期更新。因此,由于某种原因,线程在第二次调用线程时不使用BulkProcessor.getPercentComplete()获取更新值。 有人对此有任何见解吗?非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

我猜你的问题可能是因为在第二次按下按钮时,percentComplete是最大的。建议:

  • 每次运行代码时重置percentComplete。
  • 避免在后台线程中进行Swing调用,包括阅读文本字段文本。
  • 而是在SwingWorker的构造函数中执行此操作,而不是在doInBackground(...)方法中执行此操作。
  • 您似乎正在进行静态字段和/或方法调用。如果是这样,请不要这样做,因为这最终会咬你,而是创建并传递有效的引用。
  • 我猜想要这样做,你需要创建一个新的BulkProcessor对象。
  • 在你正在做的时候调用run()然后调用update(),让两个线程同时运行对我来说很危险,可能会设置一个竞争条件。

修改

您应该考虑将SwingWorker的progress属性与PropertyChangeListener一起使用。例如:

public class FooGUI {

   // .....

   public void myRun() {
      String text1 = someTextField.getText();
      String text2 = otherTextField.getText();
      final BulkProcessor bulkProcessor = new BulkProcessor(text1, text2);
      bulkProcessor.addPropertyChangeListener(new PropertyChangeListener() {

         @Override
         public void propertyChange(PropertyChangeEvent pcEvt) {
            if (pcEvt.getPropertyName().equals("progress")) {
               int progress = bulkProcessor.getProgress();
               someProgressBar.setValue(progress);
            }
         }
      });
   }
}

class BulkProcessor extends SwingWorker<Void, Void> {
   private Random random = new Random(); // just for SSCCE sake
   private String text1;
   private String text2;

   public BulkProcessor(String text1, String text2) {
      this.text1 = text1;
      this.text2 = text2;
      // not sure what you do with these texts....
   }

   @Override
   protected Void doInBackground() throws Exception {
      int progress = 0;
      while (progress <= 100) {
         progress = random.nextInt(5); // just as a for instance
                                    // your code will do something else of course
         setProgress(progress);
         Thread.sleep(300);
      }
      return null;
   }

}

例如:

import java.awt.event.*;
import java.beans.*;
import java.util.Random;
import javax.swing.*;

@SuppressWarnings("serial")
public class Foo3 extends JPanel {
   private static final String DEFAULT_SPEED = "15";
   private JTextField speedTextField = new JTextField(DEFAULT_SPEED, 5);
   private JProgressBar someProgressBar = new JProgressBar();
   private RunAction runAction = new RunAction();
   private JButton runButton = new JButton(runAction);

   public Foo3() {
      speedTextField.setAction(runAction);

      add(new JLabel("Speed:"));
      add(speedTextField);
      add(someProgressBar);
      add(runButton);
   }

   public void myRun() {
      String speedText = speedTextField.getText();
      try {
         int speed = Integer.parseInt(speedText);
         final BulkProcessor bulkProcessor = new BulkProcessor(speed);
         bulkProcessor.addPropertyChangeListener(new PropertyChangeListener() {

            @Override
            public void propertyChange(PropertyChangeEvent pcEvt) {
               if (pcEvt.getPropertyName().equals("progress")) {
                  int progress = bulkProcessor.getProgress();
                  someProgressBar.setValue(progress);
               }
               if (pcEvt.getPropertyName().equals("state")) {
                  if (bulkProcessor.getState().equals(
                        SwingWorker.StateValue.DONE)) {
                     someProgressBar.setValue(0);
                     setGuiEnabled(true);
                  }
               }
            }
         });
         setGuiEnabled(false);
         bulkProcessor.execute();
      } catch (NumberFormatException e) {
         String text = "Speed of " + speedTextField.getText()
               + " is invalid. Please enter an integer";

         JOptionPane.showMessageDialog(this, text, "Invalid Speed Value",
               JOptionPane.ERROR_MESSAGE);
         speedTextField.setText(DEFAULT_SPEED);
      }
   }

   private class RunAction extends AbstractAction {
      public RunAction() {
         super("Run");
         putValue(MNEMONIC_KEY, KeyEvent.VK_R);
      }

      @Override
      public void actionPerformed(ActionEvent arg0) {
         myRun();
      }

   }

   private void setGuiEnabled(boolean enabled) {
      runButton.setEnabled(enabled);
      speedTextField.setEnabled(enabled);
   }

   private static void createAndShowGui() {
      Foo3 mainPanel = new Foo3();

      JFrame frame = new JFrame("Foo3");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class BulkProcessor extends SwingWorker<Void, Void> {
   private Random random = new Random(); // just for SSCCE sake
   private int speed;

   public BulkProcessor(int speed) {
      this.speed = speed;
   }

   @Override
   protected Void doInBackground() throws Exception {
      int progress = 0;
      while (progress <= 100) {
         progress += random.nextInt(speed);
         setProgress(progress);
         Thread.sleep(300);
      }
      return null;
   }

}

答案 1 :(得分:0)

因此发现将while(percentComplete&lt; 100)更改为while(percentComplete&lt; = 100)会使线程永久运行。这实际上解决了这个问题,但可能不会推荐。