Rslnn
Rslnn

Reputation: 21

How to add mouse events to the drawing object in Java?

In my program, at the beginning I want the ball to be stagnant and start the action when the mouse is clicked.

What method do I need to follow?

I tried following:

 public class Ball extends Applet implements Runnable{

        int x=200;
        int y=450;
        int dx=10;
        int dy=10;
        int r=30;
        private Image i;
        private Graphics graph;
        @Override
        public void init() {

            setSize(500,500);

        }

        @Override
        public void start() {
            Thread t1=new Thread(this);
            t1.start();

        }
        @Override
        public void run() {

           while(true){
               if(x+dx>this.getWidth()-r){
                   x=this.getWidth()-r;
                   dx=-dx;
               }
               else if(x+dx<0){
                   x=0;
                   dx=-dx;
               }
               else{
                   x+=dx; 
               }
                if(y+dy>this.getHeight()-r){
                   y=this.getHeight()-r;
                   dy=-dy;
               }
               else if(y+dy<0){
                   y=0;
                   dy=-dy;
               }
               else{
                   y+=dy; 
               }
               repaint();
               try {
                   Thread.sleep(50);
               } catch (InterruptedException ex) {
                   ex.printStackTrace();
               }

           }
        }



        @Override
        public void stop() {

        }

        @Override
        public void destroy() {

        }

        @Override
        public void update(Graphics g) {
            //double buffering
            if(i==null){

                i=createImage(this.getSize().width,this.getSize().height);
                graph=i.getGraphics();
            }

            graph.setColor(getBackground());
            graph.fillRect(0, 0, this.getSize().width, this.getSize().height);
            graph.setColor(getForeground());
            paint(graph);
            g.drawImage(i, 0, 0, this);

        }

        @Override
        public void paint (Graphics g){

            g.setColor(Color.PINK);
            g.fillOval(x, y, r, r);
        }


    }

Upvotes: 0

Views: 69

Answers (1)

BinaryDump
BinaryDump

Reputation: 477

You must add a Mouse Listener, in your case you can check the method mousePressed or mouseClicked

Check here.

You can create your MouseListener MouseListener ms = new MouseListener(); it will generate the methods of the MouseListener, then you just have to modify the one that you want ( mousePressed or mouseClicked ), to finish do not forget to add the MouseListener to the object that you want to be listened object.addMouseListener(ms);

Upvotes: 2

Related Questions