How to get a JButton to change color for a period of time before reverting to its original color

Viewed 85

I wanted to create a calculator whose keys change color when pressed and return to their initial colors(white) after 3000 milliseconds. For that, I implemented the JButton.setBackground() method and wrote code to make the key revert to its original color after 3000 milliseconds. But instead, every time I click a calculator key, it waits 3000 ms before returning the JButton value to me, it changes color but it doesn't revert to its original color. I tried several maneuvers but without success. Here is my code for the JButton to change color for a given before returning to its initial color:

try {
    buttonOne.setBackground(Color.RED) ;
    Thread.sleep(millis:3000) ;
    buttonOne.setBackground(Color.WHITE);
} catch (InterruptedException interruptedException ) {
    InterruptedException.printStackTrace();
}
1 Answers

You don't want to use Thread.sleep() in your UI, because you want the UI to stay responsive.

Try something like this:

import javax.swing.Timer;

JButton buttonOne = new JButton("Click me");
Timer timer = new Timer(3000 ,afterButtonClicked);
timer.setRepeats(false);

ActionListener afterButtonClicked = new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        buttonOne.setBackground(Color.WHITE);
    }
};

In the action listener on your button:

buttonOne.setBackground(Color.RED);
timer.start();
Related