The method placePiece correctly places an ImageIcon on a JButton. I would like the image to remain there for one second and then be replaced with a different colored ImageIcon. The problem with the following code is that the red ImageIcon never appears. The delay takes place and then the black ImageIcon appears. I would like the red ImageIcon to appear, then have a 1 second delay, and then the black one appear. Thanks in advance for any help.
placePiece(0, 3, "red");
//delay 1 second here
try
{
Thread.sleep(1000);
}
catch (Exception exc) { }
placePiece(0, 3, "black");
I would suggest you using Java's javax.swing.Timer
.
There is a tutorial here: https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html
In the timer, you can easily get the interval by setting it in the parameter under speed
as shown below.
int speed = 1000; //delay of 1 second
timer = new Timer(speed, obj);
Further more, when you use Thread.sleep(1000)
, there is no guarantee that it will always be delayed by 1 second.
You may use like
placePiece(0, 3, "red");
int delay = 1000;
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
placePiece(0, 3, "black");
}
};
new Timer(delay, taskPerformer).start();
Thread.sleep()
is not good practice with swing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.