-1

i'm trying to set a delay when a button is pressed to set an imageicon to a certain image then set another delay so that another image would be set, all of this by single click. in other word :

click a button->set image->delay->set another image.

what i get in my code is the last state only "set another image".

also i don't want to use use timers, i want to use delays.

and here the part in my code i'm concerned about.

btnNewButton.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
    lblNewLabel.setIcon(and);   
sleeep(500);
        lblNewLabel.setIcon(app);
    }
});

and here is the delay function

 void sleeep(int n)
{
    try {
        Thread.sleep(n);
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Youssef Fotouh
  • 29
  • 1
  • 1
  • 5

2 Answers2

1
  1. don't add MouseListener to JButton, nor for mouseClicked(), add ActionListener instead, btw all Mouse and Key events are implemented in JButton API and correctly

  2. don't to use Thread.sleep(n); you have an issue with Concurency in Swing, use Swing Timer instead,

mKorbel
  • 109,525
  • 20
  • 134
  • 319
0

You should try executing the code that sets the image in the event dispatch thread using InvokeLater.

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        lblNewLabel.setIcon(and);
    }
});

sleeep();

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        lblNewLabel.setIcon(and);
    }
});
Luke
  • 409
  • 3
  • 12
  • 1
    It won't work reliably, as long as you don't do the `sleep` on another thread, and *then* schedule the `invokeLater` to set the last icon. – Harald K Nov 13 '13 at 13:21