为什么我的JFrame没有更新

时间:2013-05-10 13:58:40

标签: java multithreading swing event-dispatch-thread jprogressbar

我有一段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上。我很确定这是一个线程问题,但我似乎无法弄明白。我们将不胜感激。

1 个答案:

答案 0 :(得分: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