组件在绘制之前等待稍后的代码执行

时间:2015-12-29 00:45:00

标签: java swing jdialog jprogressbar

我有一个名为WaitBox的类,我想弹出,显示进度条,然后在进度条达到100%时关闭。现在,它会弹出,但奇怪的是它等到代码完成后才能在WaitBox中绘制组件(进度条)......

当我运行下面的代码时,JDialog会弹出,但它只是白色,就像在它上面绘制组件之前的样子一样。它运行在它下面的编码(嵌套for循环),当它完成时,它绘制JDialog上的组件。为什么会发生这种情况,我该如何解决?

WaitBox类:

public class WaitBox extends JDialog implements Runnable {
private static final long serialVersionUID = 1L;

private int width = 450;
private int height = 200;
public static int widthOfBar = 400;
private int heightOfBar = 50;
private JPanel container;
private JProgressBar progressBar;
private Thread thread;
private boolean running = false;

public WaitBox() {
    initializeComponents();
    add(container);
    pack();
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    setTitle("Loading...");
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setResizable(false);
    setLocationRelativeTo(null);
    setVisible(true);
}

private void initializeComponents() {
    container = new JPanel();
    container.setPreferredSize(new Dimension(width, height));
    progressBar = new JProgressBar(0, widthOfBar);
    progressBar.setPreferredSize(new Dimension(widthOfBar, heightOfBar));
    progressBar.setStringPainted(true);
    progressBar.setValue(0);
    container.add(progressBar);
}

public void run() {
    while (running) {
        System.out.println(Fill.currentPos);
        progressBar.setValue((int) Fill.currentPos);
        if (progressBar.getValue() >= widthOfBar) running = false;
    }
    stop();
}

public synchronized void start() {
    running = true;
    thread = new Thread(this);
    thread.start();
}

public synchronized void stop() {
    running = false;
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    setCursor(null);
    dispose();
}

}

如何调用

WaitBox waitBox = new WaitBox();
waitBox.start();
for (int yy = 0; yy < Constants.map_height; yy++) {
    for (int xx = 0; xx < Constants.map_width; xx++) {
        image.setRGB(xx * 32, yy * 32, 32, 32, pixels, 0, 32);
    }
}

1 个答案:

答案 0 :(得分:3)

您的stop方法正在等待thread结束,这会阻止事件调度线程。

有关详细信息,请参阅Concurrency in Swing

您的run方法违反了Swing的单线程规则,从事件调度线程外部更新UI,请记住,Swing是单线程的,但也不是线程安全的。

您应该考虑使用SwingWorker代替,该代理具有进度和PropertyChange支持。有关详细信息,请参阅Worker Threads and SwingWorker

证明了这一点:

其他地方