I'm having an issue with my GUI when I try to change the color of a button after 2 seconds when its has been clicked. What I want to do is to click on a white square button, then a color comes up, after 2 seconds I want it to return to it's original color (white). How can achieve this?
My code on click:
cards[index].setBackground(cards[index].getTrueColor());
try
{
Thread.sleep(2000);
cards[cardPos.get(0)].setBackground(Color.whi开发者_JAVA百科te);
}
catch(Exception e) {}
So this goes back to color white, but in an instance, doesn't wait to seconds. Really appreciate a little help here. Thanks!
This calls for a Timer
instead of Thread.sleep
. You'll want to set the timer with a delay of 2 seconds, and then have it reset the color of your button. For example, in Swing:
// onButtonClick
final Card card = cards[index];
card.setBackground(card.getTrueColor());
new Timer(2000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Change color back
card.setBackground(Color.WHITE);
}
}).start();
- How to Use Swing Timers
You can use the AsynkTask class in Android. You can use the onPreExecute method to execute the initial task, and then you can wait and change the button color after 2 sec, this can be done in doInBackground method and you can publish the results to UI by calling publish progress method, and finally you can use the onPostExecute method.
http://developer.android.com/reference/android/os/AsyncTask.html
精彩评论