所以,我想弄清楚如何在我的纸牌游戏中添加暂停以使CPU像轮流转动一样。但是,涉及的代码太多,所以我认为如果我们在这个代码上演示策略,它可以工作。如何让这个项目在按下按钮后暂停一段时间
如何让此代码暂停,例如按下按钮5秒后,然后打印消息。
public class TimerTest extends JFrame implements ActionListener{
private static final long serialVersionUID = 7416567620110237028L;
JTextArea area;
Timer timer;
int count; // Counts the number of sendings done by the timer
boolean running; // Indicates if the timer is started (true) or stopped (false)
public TimerTest() {
super("Test");
setBounds(30,30,500,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(null);
area = new JTextArea();
area.setBounds(0, 0, 500, 400);
add(area);
JButton button = new JButton("Click Me!");
button.addActionListener(this);
button.setBounds(200, 400, 100, 40);
add(button);
// Initialization of the timer. 1 second delay and this class as ActionListener
timer = new Timer(5000, this);
timer.setRepeats(true); // Send events until someone stops it
count = 0; // in the beginning, 0 events sended by timer
running = false;
System.out.println(timer.isRepeats());
setVisible(true); // Shows the frame
}
public void actionPerformed(ActionEvent e) {
if (! running) {
timer.start();
running = true;
}
// Writing the current time and increasing the cont times
area.append(Calendar.getInstance().getTime().toString()+"\n");
count++;
if (count == 10) {
timer.stop();
count = 0;
running = false;
}
}
public static void main(String[] args) {
// Executing the frame with its Timer
new TimerTest();
}
}
我真正想要做的是能够在运行每个CPU的动作的方法中插入一个暂停。但是,听起来像是用Timer类,你需要在Timer的动作监听器中执行你的post-pause动作。我最关心的是为什么Timer需要一个actionListener。完成后,我不需要定时器重复。
如果我发布自己的代码会更好,请告诉我。但我不确定哪些部分是有用的,因为我不想在此线程中拥有大量的代码。
尝试增加'的Thread.sleep(5000);'? –
Swing'Timer'有什么问题?如果将其设置为不重复,延迟时间为5000,则可以调用另一种方法在指定的时间段后执行所需的任何操作? – MadProgrammer
@DarshanMehta您可能并不知道在Swing或JavaFX中使用Thread.sleep或与任何UI框架相关的危险和问题,这不是一个好主意,并且对于所有额外的麻烦,您不应该推荐它对于这个用例 – MadProgrammer