问题
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.
回答1:
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);
});
}
来源:https://stackoverflow.com/questions/58121425/pausing-execution-of-code-in-the-actionperformed-method-of-actionlistener