1

我有一段 JFrame 代码,它将向用户显示图像导入期间的进度:

public class LoadFrame implements Runnable {

    JProgressBar progressbar;
    JPanel loadpanel;
    MainScreen mainscreen;
    int progress;
    JDialog mainloadframe;

    public LoadFrame(String operation) {

        mainloadframe = new JDialog();
        JLabel operationlabel = new JLabel(operation);
        progressbar = new JProgressBar(0, 100);
        loadpanel = new JPanel();

        mainloadframe.setSize(300, 75);
        mainloadframe.setLocationRelativeTo(null);
        mainloadframe.setLayout(new GridLayout(1, 2));
        mainloadframe.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        mainloadframe.setAlwaysOnTop(true);
        mainloadframe.setTitle(operation);
        mainloadframe.setVisible(true);

        progressbar.setValue(0);
        progressbar.setStringPainted(true);
        loadpanel.add(progressbar);
        loadpanel.add(operationlabel);
        mainloadframe.add(loadpanel);

    }

    public void setMainScreen(MainScreen mainscreen) {
        this.mainscreen = mainscreen;
    }

    public void disposeLoadFrame() {
        mainloadframe.dispose();
    }

    public void setProgress(int progress) {
        this.progress = progress;
    }

    @Override
    public void run() {
        while (progress != 100) {
            progressbar.setValue(progress);
        }
    }
}

进度的实际计算也是在一个线程中完成的,但由于某种原因,直到图像完成导入,进度条才会显示在 JFrame 上。我很确定这是一个线程问题,但我似乎无法弄清楚。一点帮助将不胜感激。

4

1 回答 1

2
  • Runnable#Thread不是start()

  • (发布到论坛)必须添加Thread.sleep(int)run(),然后progressbar.setValue(progress);必须被包裹到invokeLater()

  • 通过使用 util.Timer 而不是 Runnable#Thread ,然后progressbar.setValue(progress);最好被包装成invokeLater()


  • 通过使用Swing Timer

  • 正确的方法是progressbar.setValue(progress);SwingWorker
于 2013-05-10T14:05:14.473 回答