问题描述
我有这个actionPerformed
方法可以抓两张牌.在这两张牌的抽签之间,我想暂停程序一定时间,以便能够一张一张地看到卡的抽签.我尝试了Thread.sleep()
方法,但是在执行actionPerformed
方法后它只是暂停了程序.
I have this actionPerformed
method that draws two cards. In between of drawing of those two cards I want to pause the the program for a certain amount of time so that I will be able see drawing of cards one by one. I tried Thread.sleep()
method but it just pauses the program after the execution of actionPerformed
method.
推荐答案
由于Swing事件线程中的长时间运行操作(如暂停)将冻结UI,因此不建议使用此策略.相反,可以考虑使用 Timer 来触发与第二张卡片的图形相对应的第二个事件,如下例所示.
Because a long-running operation (like pausing) in the Swing event thread will freeze the UI, this is not a recommended strategy. Instead, maybe consider using a Timer to fire a second event that corresponds to the drawing of the second card, as in the example below.
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);
});
}
这篇关于在ActionListener的actionPerformed()方法中暂停执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!