I have a game where I want to flash a component a red color, and then back to its normal color after a short delay. Obviously, I could just do Thread.sleep(123)
, but that is EXTREMELY undesirable because it breaks stuff on my UI. Plus, I am pretty sure that is not what I am supposed to do here.
Now, I could just do the pause off the queue, and then use SwingUtilities::invokeLater
. But I wanted to ask to learn the best practices here.
What is the best way to add a specific length pause in between Swing/AWT Events?
Here is a runnable example.
import javax.swing.*;
import java.awt.*;
public class cry {
public static void main(final String[] args) {
SwingUtilities.invokeLater(cry::blah);
}
private static void blah() {
final JFrame frame = new JFrame();
frame.setTitle("ABC");
frame.setLocationByPlatform(true);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
try {
Thread.sleep(10_000); //sleep for 10 seconds
} catch (Exception e) {
throw new RuntimeException(e);
}
frame.setTitle("XYZ");
}
}
javax.swing.Timer
manage the waiting, for example.Timer
"perform their waiting using a single, shared thread," so multiple timers are feasible; now that you know what to look for, please edit your question to include a minimal reproducible example that shows your revised approach.