James MV
James MV

Reputation: 8717

Switch Java Button image back and forth?

I have a program that uses a switch which has the action event passed to it on button click:

public void buttonImageReveal(ActionEvent e){

    String temp = e.getActionCommand();

    switch(temp){

        case "1":
        ((JButton)e.getSource()).setIcon(one);
        delay();
        ((JButton)e.getSource()).setIcon(null);
        break;

Delay is just a call to a function with a 1 second wait:

 public void delay(){
        try
        {
            Thread.sleep(1000); 
        }
            catch(InterruptedException e1)
        {
            e1.printStackTrace();
        }
    }

All that results is a wait and no image, the desired outcome is a flash of the image for a second.

Thanks in advance!

Upvotes: 1

Views: 709

Answers (1)

Ashwinee K Jha
Ashwinee K Jha

Reputation: 9317

After setting the icon you are making the thread sleep so it can't paint the new icon. Immediately after sleep is over you set icon to null. So you will never see the icon painted.

You can try to change the icon using javax.swing.Timer periodically.

Upvotes: 5

Related Questions