Java 暂停ActionListener的actionPerformed()方法中的代码执行
我执行了这个Java 暂停ActionListener的actionPerformed()方法中的代码执行,java,swing,event-handling,Java,Swing,Event Handling,我执行了这个操作方法,可以画两张牌。在这两张卡片的绘制之间,我想将程序暂停一段时间,以便我能够逐个查看卡片的绘制。我尝试了Thread.sleep()方法,但它只是在执行actionPerformed方法后暂停程序 由于Swing事件线程中的长时间运行操作(如暂停)将冻结UI,因此不建议使用此策略。取而代之的是,可以考虑使用A来触发与第二张卡片相对应的第二个事件,如下面的例子。 public static void main(String[] args) { SwingUtilities
操作
方法,可以画两张牌。在这两张卡片的绘制之间,我想将程序暂停一段时间,以便我能够逐个查看卡片的绘制。我尝试了Thread.sleep()
方法,但它只是在执行actionPerformed
方法后暂停程序 由于Swing事件线程中的长时间运行操作(如暂停)将冻结UI,因此不建议使用此策略。取而代之的是,可以考虑使用A来触发与第二张卡片相对应的第二个事件,如下面的例子。
public static void main(String[] args) {
SwingUtilities.invokeLater(()-> {
JFrame frame = new JFrame();
JButton button = new JButton("Ok");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("First card");
Timer timer = new Timer(2000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Second card");
}
});
timer.setRepeats(false);
timer.start();
}
});
frame.add(button);
frame.pack();
frame.setVisible(true);
});
}
由于Swing事件线程中的长时间运行操作(如暂停)将冻结UI,因此不建议使用此策略。取而代之的是,可以考虑使用A来触发与第二张卡片相对应的第二个事件,如下面的例子。
public static void main(String[] args) {
SwingUtilities.invokeLater(()-> {
JFrame frame = new JFrame();
JButton button = new JButton("Ok");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("First card");
Timer timer = new Timer(2000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Second card");
}
});
timer.setRepeats(false);
timer.start();
}
});
frame.add(button);
frame.pack();
frame.setVisible(true);
});
}