0

I am new to java, I think this might be simple but I couldn't find the answer to my question anywere, maybe because I didn't phrase it right. I have this simple pseudo code, if I run it, it will seem as if nothing happens , I want the user to be able to see(icon2) for a few seconds, before it is changed back to icon.

I tried Thread.sleep but it didn't work, it worked on whatever else is inside (if) like a simple (print) but doesn't work on the interface. I think because it is in a the different thread, because I used Netbeans to create a frame class.

 ImageIcon icon = new ImageIcon("somepath");
  jLabel.setIcon(icon); //i give my label some icon
  jLabel.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent evt) {
 ImageIcon icon2 = new ImageIcon("some_otherpath");
  jLabel1.setIcon(icon2); // The user clicks on the label so the icon changes
 if(condition){            //if some condition is true i want the icon to change back
  jLabel1.setIcon(icon); // if condition is not true, the label keeps icon2 
                         // but i want the user to be able to see the change. 
    } 
 }
   });

Thank you in advance.

  • If anyone has any better way to phrase my question, I would be very thankful. – Noussa Smiley Apr 11 '18 at 19:32
  • If this is Swing UI, use a [Swing Timer](https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html). – Andreas Apr 11 '18 at 19:44
  • Possible duplicate of [using sleep() for a single thread](https://stackoverflow.com/q/14074329/5221149) – Andreas Apr 11 '18 at 19:47
  • The problem here is that you called setIcon twice, and the UI will be updated only after the method ends, so you will effectivelly see only the last change. You have to show one, then wait in a secondary thread (keeping the UI free to update) then show the second. – Marcos Vasconcelos Apr 11 '18 at 19:47
  • @MarcosVasconcelos I don't understand, are you telling me that the icon never changed to icon2, and the problem is not that we can't see the change? – Noussa Smiley Apr 11 '18 at 20:26
  • @Andreas Thank you very much, I tried using Timer before, but I guess I did it wrong cause it didn't work for me. Thank you again. – Noussa Smiley Apr 11 '18 at 20:36

1 Answers1

0

Try using Java ScheduledExecutorService:

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    Runnable task = new Runnable() {
        public void run() {
            //Your 'if' condition here
        }
    };

    int delay = 3; //delay 3 seconds, or whatever
    scheduler.schedule(task, delay, TimeUnit.SECONDS);
    scheduler.shutdown();
...

This program simply waits 3 seconds before executing your if condition. While it delays, your users will see icon2. This code chunk should be placed after this line jLabel1.setIcon(icon2);

  • Thank you so much. I never even heard about this class, I would have never thought of something like this. thank you again. – Noussa Smiley Apr 11 '18 at 20:18