Thread#sleep在 主 线程中的swing应用程序中使用method
会导致GUI冻结(因为该线程处于睡眠状态,因此无法发生事件)。
Thread#sleepSwing应用程序中的Swing方法仅允许SwingWorkers使用,并且只能在其
#doInBackround方法中使用。
为了在Swing应用程序中等待(或定期执行某些操作),您将必须使用Swing计时器。看我做的一个例子:
import java.awt.FlowLayout;import java.util.Date;import javax.swing.JButton;import javax.swing.Jframe;import javax.swing.SwingUtilities;import javax.swing.Timer; //Note the importpublic class TimerExample extends Jframe { private static final int TIMER_DELAY = 1000; private Timer timer; public TimerExample () { super(); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(200, 200); setLocationRelativeTo(null); getContentPane().setLayout(new FlowLayout()); timer = new Timer(TIMER_DELAY, e -> { System.out.println("Current Time is: " + new Date(System.currentTimeMillis())); }); //timer.setRepeats(false); //Do it once, or repeat it? JButton button = new JButton("Start"); button.addActionListener(e -> timer.start()); getContentPane().add(button); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> new TimerExample().setVisible(true)); }}按下“开始”按钮后的输出:
当前时间是:2019年2月25日星期一13:30:44
当前时间是:EET 2019星期一2月25日13:30:45
当前时间是:EET 2019星期一2月25日13:30:46
如您所见,Timer的动作侦听器每秒触发一次。
因此,在您的情况下:
timer = new Timer(TIMER_DELAY, e -> { if (currentIndexLabel != paint.length-1) { upateLabels(); timer.restart(); //Do this check again after 1000ms }});button.addActionListener(e -> timer.start());


