JProgressBar没有更新,找不到线索

The*_*Ero 3 java oracle swing multithreading jprogressbar

很好的工作,现在我只想知道为什么如果我加入while循环指令System.out.println下面的进度显示在两个,cmd和Pgbar在桂?:

while(progress < 99){ 
  System.out.println("into while of PBar Thread progress = "+progress); 
  if(progress != Path.operationProgress){ 
    operationProgressBar.setValue(progress); 
    progress = Path.operationProgress; 
    operationProgressBar.repaint(); } }
Run Code Online (Sandbox Code Playgroud)

需要一些帮助,我不能让JProgressBar更新,我不能使用SwingWorker,我必须解决这个没有它.变量Path.operationProgress是来自"Path"类实例的静态变量,它是从另一个线程更新的,所以我认为PBar和Path实例都是在用户的线程中执行而不是在EDT中执行.这是进度条的代码:

    import javax.swing.*;
    public class Pbar extends Thread {
      JProgressBar operationProgressBar;
      public Pbar(JProgressBar operationProgressBar) {
          this.operationProgressBar = operationProgressBar;
      }

      @Override
      public void run() {
          int progress = Path.operationProgress;
          while(progress < 99) {
              if(progress != Path.operationProgress) {
                  operationProgressBar.setValue(progress);
                  progress = Path.operationProgress;
                  operationProgressBar.repaint();
              }}}
     }
Run Code Online (Sandbox Code Playgroud)

这是启动线程的操作:

private javax.swing.JProgressBar operationProgressBar;
private javax.swing.JLabel pathImage;
private javax.swing.JButton simulatedAnnelingButton;

public class TSPGUI extends javax.swing.JFrame {

    TSPMG tspInstance;
    Path p, result;
    String filename = "";
    int neighborHood_Type = 1, i = 0;
    // ......Constructor Stuff and init()

private void simulatedAnnelingButtonActionPerformed(java.awt.event.ActionEvent evt)
Run Code Online (Sandbox Code Playgroud)

{
Thread sa = new Thread(){@ Override public void run(){result = p.SimulatedAnnealing(neighborHood_Type); String lastCostString = result.Cost()+""; lastCostLabel.setText(lastCostString); }}; sa.start(); Pbar pb = new Pbar(operationProgressBar); pb.start(); } //其他一些东西......}

Hau*_*idt 5

如果你不能使用SwingWorker那么使用SwingUtilities.invokeLater,例如:

if (progress != Path.operationProgress) {
    final int progressCopy = progress; // Probably not final so copy is needed
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        void run() {
            operationsProgressBar.setValue(progressCopy);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

注意:执行此操作时,所使用的所有内容run都必须是最终的,或者必须有其他措施来访问变量.在这方面,这段代码具有象征意义.

你需要在事件调度线程之外对Swing组件进行操作,没有办法解决这个问题.