Croviajo
Croviajo

Reputation: 249

display an icon in a JButton and hide it

I have a JButton, and I want when I click to this button to display an icon in it then after 3 seconds to hide the icon and display a text in the button.

in the action listener I tried this code :

JButton clickedButton = (JButton) e.getSource();
clickedButton.setIcon(new ImageIcon(images.get(clickedButton.getName())));
try {
    Thread.sleep(3000);                
} catch(InterruptedException ex) {
    Thread.currentThread().interrupt();
}
clickedButton.setText("x");
clickedButton.setIcon(null);

The problem is that when I click in the button the program blocks for 3 minutes then the text "x" displayed in the button.

How can I solve this problem ?

Upvotes: 0

Views: 1510

Answers (2)

Amarnath
Amarnath

Reputation: 8865

As suggested you don't need to use Thread.Sleep use Swing Timer to perform this task.

 // Declare button and assign an Icon.
 Icon icon = new ImageIcon("search.jpg");
 JButton button = new JButton(icon);    
 ChangeImageAction listener = new ChangeImageAction(button);
 button.addActionListener(listener);

Below ChangeImageAction class will do the necessary action when the button is clicked. When you click on the button an action is fired and in this action we will call the Timer's Action listener where we set the button's icon as null and give the button a title.

class ChangeImageAction implements ActionListener {

    private JButton button;

    public ChangeImageAction(JButton button) {
        this.button = button;
    }

    ActionListener taskPerformer = new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            button.setIcon(null);
            button.setText("Button");
        }
    };

    @Override
    public void actionPerformed(ActionEvent arg0) {
        Timer timer = new Timer( 3000 , taskPerformer);
        timer.setRepeats(false);
        timer.start();
    }

}

P.S: I am trying Timer for the first time thanks to @Hovercraft Full Of Eels for the suggestion.

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Don't call Thread.sleep(...) on the Swing event thread since that freezes the thread and with it your GUI. Instead use a Swing Timer. For example:

final JButton clickedButton = (JButton) e.getSource();
clickedButton.setIcon(new ImageIcon(images.get(clickedButton.getName())));

new Timer(3000, new ActionListener(){
  public void actionPerformed(ActionEvent evt) {
    clickedButton.setText("x");
    clickedButton.setIcon(null);   
    ((Timer) evt.getSource()).stop(); 
  }
}).start();

Upvotes: 2

Related Questions