这里有一个例子:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        int x = 0;
        while (jProgressBar1.getValue() < 100) {
            try {
                Thread.sleep(50);
                x++;
                jProgressBar1.setValue(x);
                jProgressBar1.repaint();
            } catch (InterruptedException ex) {
                Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println(jProgressBar1.getValue());
        }
    }


System.out.println(jProgressBar1.getValue());将数字返回到IDE输出,但是jProgressBar1不会绘制此值。此代码有什么问题?请帮忙。

最佳答案

切勿在Swing线程中使用Thread.sleep()。请改用javax.swing.Timer。

例:

private void jButton1ActionPerformed(ActionEvent evt) {
    final Timer t = new Timer(50, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            jProgressBar1.setValue(jProgressBar1.getValue() + 1);
            if (jProgressBar1.getValue() == 100) {
              ((Timer) e.getSource()).stop();
            }
        }
    });
    t.start();
}

07-27 22:48