小编典典
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 import
public 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(