1 Replies - 3010 Views - Last Post: 27 May 2011 - 07:16 AM Rate Topic: -----

#1 harmy01  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 15
  • View blog
  • Posts: 179
  • Joined: 15-June 10

Moving a rectangle on Jpanel

Posted 27 May 2011 - 06:09 AM

Hey guys.

I am trying to move a rectangle around JPanel. but having problems, what happens is that the rectangle only moves to 1 direction.

Here is the code I've been using

import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author Josh Anderson
 */
public class Canvas extends JPanel implements MouseMotionListener {

    Rectangle rec1 = new Rectangle();
    Rectangle rec2 = new Rectangle();

    //Constructor 
    public Canvas() {
        rec1.setLocation(70, 70);
        rec2.setLocation(100, 100);
        this.addMouseMotionListener(this);

    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawRect(rec1.x, rec1.y, 20, 20);
        g.drawString("1", rec1.x, rec1.y);
        g.drawRect(rec2.x, rec2.y, 20, 20);
        g.drawString("2", rec2.x, rec2.y);
        g.drawLine(rec1.x, rec1.y, rec2.x, rec2.y);
    }

    @Override
    public void mouseDragged(MouseEvent e) {

        Rectangle rec3 = new Rectangle(e.getX()-20, e.getY()-20, 20, 20);
        if (rec3.contains(rec1.getLocation())) {
            rec1.setLocation(e.getX(), e.getY());
            repaint();
        }else if(rec3.contains(rec2.getLocation())){
            rec2.setLocation(e.getX(), e.getY());
           repaint();
        }
    }

    @Override
    public void mouseMoved(MouseEvent e) {
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.add(new Canvas());

        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}


Thanks for helping guys
Cheers

Is This A Good Question/Topic? 0
  • +

Replies To: Moving a rectangle on Jpanel

#2 g00se  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2555
  • View blog
  • Posts: 10,655
  • Joined: 20-September 08

Re: Moving a rectangle on Jpanel

Posted 27 May 2011 - 07:16 AM

You need a MouseListener too. See example at

http://www.java2s.co...pewithmouse.htm
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1