0

I am trying to start a small animation on mouse click ...here is my code

import acm.graphics.*;
import acm.program.*;
import java.awt.*;
import acm.util.*;
import java.awt.event.*;

public class ClickAnimation extends GraphicsProgram {

    GOval ball=new GOval(50,50,50,50);

    public void run() {
        add(ball);
        addMouseListeners();
    }

    public void mouseClicked(MouseEvent e) {
        while(ball.getX()<getWidth()) {
            ball.move(0.2,0.2);
            pause(10);
        }
    }
}

Google says while loop cannot be used inside a mouse listener...how can i fix this?

AliciaBytes
  • 7,300
  • 6
  • 36
  • 47
  • Please share minimal testable code and explain the problem a bit more. – Braj Jun 06 '14 at 09:30
  • Call the next Method with the while inside. – Watsche Jun 06 '14 at 09:31
  • the animation(while loop) is working just fine if its is placed directly in the run method but when called through mouse listeners program is just getting stuck. so I want to make the while loop inside the mouseclicked() work.. – user3713689 Jun 06 '14 at 09:33
  • I'm not familiar with your libraries, but the essential problem is that a handler needs to return promptly, not hang out waiting forever. Instead, fire off a background job (using something like `SwingWorker` with the standard libraries) from your handler method. – chrylis -cautiouslyoptimistic- Jun 06 '14 at 09:35
  • my problem is similar to this http://stackoverflow.com/questions/20814260/move-a-ball-on-mouse-click-in-java?rq=1 all i want to know is whether a loop can be built inside a mouselistener or not.if not what to do to acheive this – user3713689 Jun 06 '14 at 13:25

1 Answers1

0

I thought I met your problem.And I figure out the reason why the loop inside a mouse listener in JAVA does not work out is because thread problem. This was explained in this link.So I solved the problem by create another threat for the while loop and it solve my problem.Hope this code below will solve your problem.

import acm.graphics.*;
import acm.program.*;
import java.awt.*;
import acm.util.*;
import java.awt.event.*;

public class ClickAnimation extends GraphicsProgram {

    GOval ball=new GOval(50,50,50,50);

    public void run() {
        add(ball);
        addMouseListeners();
    }
    
    public void mouseClicked(MouseEvent e) {
        Thread x = new Thread(new InnerBallClass());
        x.start();
    }

    public class InnerBallClass implements Runnable{
        public void run(){
            while(ball.getX()<getWidth()) {
                ball.move(0.2,0.2);
                pause(10);
            } 
        }
    }

}
earwen
  • 13
  • 4