Results 1 to 7 of 7
  1. #1
    Savantx is offline Member
    Join Date
    Mar 2011
    Posts
    6
    Rep Power
    0

    Default Thread.sleep issue

    I'm having trouble with Thread.sleep. I want my program to wait a second between actions. The problem is that the command(s) within the conditional that are above the Thread.sleep() command are also waiting before firing.

    This is my basic code:
    Java Code:
    int counter = 0;
    bool setNotSelected = true;
    
        private void label1MouseClicked(java.awt.event.MouseEvent evt) {
           
            if(iconArray[1].notSelected()&&counter==1){
    
    //    tried this inside and outside of try{}, no difference//   label1.setIcon(iconArray[1].getIcon());
              try{
                  label1.setIcon(iconArray[1].getIcon());
                  Thread.sleep(1500);
              label1.setIcon(iconArray[0].getIcon());
                counter = 0;
                     }
    catch( InterruptedException e ){}
    }
    }
    I have this code for several labels' mouseclick events. I want the program to give the label 1 icon, then wait 1.5 secs then give it the other icon, but instead it is waiting 1.5 secs to do everything within the conditional, above and below Thread.sleep. I've also tried using a wait() method with System.currentTimeMillis and get the same thing.

    Does anyone know what I am missing?

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    label1MouseClicked() - you really should change the name to something more descriptive! - is being called on the event dispatch thread. The critical thing is that things that affect your gui occur on this thread one at a time in order. On no account should this thread sleep(). As that page puts it "Tasks on the event dispatch thread must finish quickly; if they don't, unhandled events back up and the user interface becomes unresponsive."

    I want the program to give the label 1 icon, then wait 1.5 secs then give it the other icon
    Respond to the click by changing the icon and setting up a task that will change the icon again 1.5 seconds in the future. A swing timer will let you do this.

  3. #3
    Savantx is offline Member
    Join Date
    Mar 2011
    Posts
    6
    Rep Power
    0

    Default

    Thank you for the reply. I had just found out about NetBeans' Frame and Panel forms and was playing around with it. It autogenerates the code and doesn't let me rename the listeners/events which is why the names are all wonky.

    I decided to write my program out myself and hope that I could get around it but after finishing up all the other logic I still haven't figured out the timers.

    I tried this,
    Java Code:
    javax.swing.Timer t = new javax.swing.Timer(500, new ActionListener() {
    
                        public void actionPerformed(ActionEvent e) {
                            if (clicked[0].getValue() == clicked[1].getValue() && !clicked[0].isSelected()) {
                                clicked[0].suspend();
                                clicked[1].suspend();
                            } // {
                                clicked[0].flip();
                                clicked[1].flip();
                            //}
                            clicked[0] = null;
                            clicked[1] = null;
                            turn = 0;
                            System.out.print("wait");
                        }
                    });
                    t.setDelay(500);
                    t.setRepeats(false);
                    t.start();
    and I get a pause before the print command fires but the rest of the code in the event handler is being skipped over it seems. I want the whole program to pause for the ~1 second, not just the one action...or at least not allow any more cards to be flipped.(doing a simple memory game) The only thing I can think of is to create a second thread and use t.wait(long timeout, int nanos); But I'm not entirely sure how to use it. I tried sending null for the long argument but no dice.

    I'm going to keep trying to figure it out.

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    I'm not very familiar with NB, but I would be surprised if it does not let you set variables rather than accepting the defaults provided by the IDE. That controlling the autogenerated code adds another task quite unrelated to what you are aiming to do is one reaon why people starting to write guis are advised to write the code themselves.

    I get a pause before the print command fires but the rest of the code in the event handler is being skipped over it seems. I want the whole program to pause for the ~1 second, not just the one action.
    I can't comment - based on the code you've posted - about code being "skipped over". But the guiding principle to keep in mind is that guis do not sleep: they remain responsive always although the response they give might depend on the state of the application. The "whole program" ought not to pause.

    To make certain buttons and things aware that the state of the program is such that they should not do anything:

    * in the event handler set a flag to mark the app as paused. Then create a timer to handle the event after a suitable delay.
    * other gui elements should check this flag before deciding what to do
    * the action event of the handler should reset the flag

    Care should be taken so that any setting/unsetting of the flag marking the app as paused takes place on the event dispatch thread.

    An alternative would be for the event handler to disable parts of the gui, and the timer's action event to enable them again after the delay.

    ---------

    In any event, if I were you I would implement either (or both, or something else suggested by anyone else, or something else you dream up yourself) in a small application: say a couple of buttons one of which has the effect of making the other unresponsive for a brief period of time. Once you have the logic correct you can incorporate it into your larger application.

    [edit] read more closely and seen what the "print command" is. yes it is delayed (rather than paused).
    Last edited by pbrockway2; 08-18-2011 at 02:55 AM.

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by Savantx View Post
    Thank you for the reply. I had just found out about NetBeans' Frame and Panel forms and was playing around with it. It autogenerates the code and doesn't let me rename the listeners/events which is why the names are all wonky.
    This is most definitely not true. You are free to rename them and should do this at the first opportunity. If you still plan to use NetBeans, please read the help files to see how to do this.

    I decided to write my program out myself and hope that I could get around it but after finishing up all the other logic I still haven't figured out the timers.

    I tried this,
    Java Code:
    javax.swing.Timer t = new javax.swing.Timer(500, new ActionListener() {
    
                        public void actionPerformed(ActionEvent e) {
                            if (clicked[0].getValue() == clicked[1].getValue() && !clicked[0].isSelected()) {
                                clicked[0].suspend();
                                clicked[1].suspend();
                            } // {
                                clicked[0].flip();
                                clicked[1].flip();
                            //}
                            clicked[0] = null;
                            clicked[1] = null;
                            turn = 0;
                            System.out.print("wait");
                        }
                    });
                    t.setDelay(500);
                    t.setRepeats(false);
                    t.start();
    You've set repeats to false and you want your timer to be repeating if you want it to change your program state every xxx msecs.

  6. #6
    Savantx is offline Member
    Join Date
    Mar 2011
    Posts
    6
    Rep Power
    0

    Default

    pbrockway2,

    Thank you for the help!

    I did what you said and made a small app and then encorporated the timer into my program, then added a pause flag for gui checks and it all works now.

    Fuberable,

    My bad, I was just messing around with the netBeans forms for the first time. From what I could/can see refactor>rename doesn't work on the event handlers the way it works for buttons and other elements. I'll have to look more into it the next time I try using the GUI Forms.

  7. #7
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    I'm glad you've got it doing what you want.

    I don't know if I expressed myself well - the reason for writing a small app that does little more than "pause" the app is twofold: to help you clarify the problem and to give us all something simple to discuss (ie free of NB and your program's logic) if things go wrong. This is what people here refer to as a SSCCE.

Similar Threads

  1. Thread.sleep
    By Gog in forum New To Java
    Replies: 3
    Last Post: 01-13-2011, 09:14 AM
  2. Difference between Thread.yield() and Thread.sleep() methods
    By Nageswara Rao Mothukuri in forum New To Java
    Replies: 12
    Last Post: 07-30-2010, 06:37 PM
  3. how to reduce the thread sleep time and wake up the thread
    By baktha.thalapathy in forum Threads and Synchronization
    Replies: 2
    Last Post: 06-24-2010, 08:36 PM
  4. Can't get my thread to sleep!
    By jamesfrize in forum New To Java
    Replies: 2
    Last Post: 03-25-2008, 06:14 AM
  5. How to use the sleep and thread?
    By jiuhu in forum Java Applets
    Replies: 4
    Last Post: 08-07-2007, 03:56 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •