0

This is my code:

@Override
    public void mousePressed(MouseEvent arg0) 
    {
        this.setIcon(obr);

        if(p.getAktivni() == null)
            p.setAktivni(this);
        else
        {
            if(this.jeStejne(p.getAktivni()))
            {
                p.nalezeno();
                this.zmiz();
            }
            else
            {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                p.nenalezeno(this);

            }
        }
    }

This points to JLabel. The problem is the Thread.Sleep() runs before the this.setIcon(obr); Why is that and how is that even possible?

rebatoma
  • 734
  • 1
  • 17
  • 32
gygabyte
  • 176
  • 2
  • 12
  • how do you know, that Thread.Sleep() runs before the this.setIcon(obr); ? – Adil Shaikh Oct 17 '15 at 11:15
  • 3
    I'm pretty sure `Thread.sleep` runs **after** `setIcon`, but the method that updates your window doesn't run then, because the thread is sleeping. – Siguza Oct 17 '15 at 11:16
  • 1
    You want to read about Swings Event dispatching thread ... you better not wait in the thread that handles **all** the actions going on in the UI. – GhostCat Oct 17 '15 at 11:18
  • It runs after `setIcon`. But when it sleeps in this method, it's not going to update the screen. Only after it left your `mousePressed` method. http://stackoverflow.com/questions/16788384/how-to-make-a-thread-not-freeze-you-whole-jframe-java – zapl Oct 17 '15 at 11:19
  • When you call `Thread.sleep(...)` on the Swing event thread, you put the entire GUI to sleep. This is a common problem, one where there are many similar questions on this site (and your mistake was in not searching this site first). A solution: use a Swing Timer to do your delay. Google the tutorial and it will explain how to use this. – Hovercraft Full Of Eels Oct 17 '15 at 12:09

0 Answers0