Results 1 to 4 of 4
  1. #1
    CBarry is offline Member
    Join Date
    Apr 2009
    Posts
    2
    Rep Power
    0

    Default Breaking for-loops with listeners?

    I have an action listener on a button that starts a for-loop. I would like to add a key listener that causes that for-loop to stop, but instead it waits for the for-loop to finish before it executes the command. How can I get this for loop to stop before it is finished iterating?

    For example:

    start, stop are Components.

    start.addMouseListener(new MouseListener(){
    method mouseClicked(){
    execute some for-loop
    }
    ......

    stop.addKeyListener(new KeyListener(){
    method keyPressed(){
    stop for-loop from the 'start' component
    }

    .......

  2. #2
    markw8500's Avatar
    markw8500 is offline Senior Member
    Join Date
    Jul 2008
    Location
    Pennsylvania, USA
    Posts
    136
    Rep Power
    0

    Default

    You want to have a boolean that becomes true when your event takes place... Then in your for loop you want to put:

    Java Code:
         if(myBoolean){
    
              break;
          }
    Who Cares... As Long As It Works...

  3. #3
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    6

    Default

    The problem is, event processing is single threaded in swing and awt. You are starting your loop from an actionlistener, which means no event processing can take place until that call returns.

    To do what you are wanting to do, you need to launch your for loop in a different thread.

  4. #4
    CBarry is offline Member
    Join Date
    Apr 2009
    Posts
    2
    Rep Power
    0

Similar Threads

  1. Help Updating Tree via Listeners
    By Seiki in forum SWT / JFace
    Replies: 1
    Last Post: 03-27-2009, 10:46 AM
  2. Seriously need help on my listeners!!
    By themburu in forum Java Applets
    Replies: 4
    Last Post: 05-26-2008, 10:41 AM
  3. Breaking down an integer
    By Emily in forum New To Java
    Replies: 1
    Last Post: 03-06-2008, 06:39 PM
  4. Replies: 2
    Last Post: 02-18-2008, 04:24 AM
  5. Breaking from nested switch
    By javaplus in forum New To Java
    Replies: 3
    Last Post: 02-02-2008, 08:28 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
  •