Changing color before removing button
I'm trying to create a button that changes color of t开发者_如何学运维he background and then removes itself from the JFrame after a set amount of time, but instead of changing color it just stays pressed for the duration of wait.
public void actionPerformed(ActionEvent e) {
setBackground(Color.red);
try{
Thread.sleep(10000);
}
catch (InterruptedException iE) {
}
frame.remove(this);
}
Can anyone see what im doing wrong?
Your sleep is occurring in the main UI thread, hence the reason the button just stays pressed. If you want a sleep you should create a new thread, get that to sleep, then from within that thread you can get the frame to remove the button.
new Thread() {
public void run() {
try {
Thread.sleep(10000);
// Now do what is needed to remove the button.
} catch (InterruptedException e) {
e.printStackTrace();
}
};
}.start();
精彩评论