使用鼠标Listener拖动对象

时间:2016-03-04 22:23:38

标签: java user-interface mouseevent mouselistener

我正在尝试创建一个程序,使用户能够在空间中拖放椭圆。我能够拖放但是在我第二次尝试再次尝试之后,椭圆形的跳跃遍布各个地方。我想知道是否有人知道为什么会这样?我错过了什么吗?谢谢

public class MoveOval extends JFrame {

private Ellipse2D node = new Ellipse2D.Float(200,200,80,120);
private Point offset;
private int preX,preY;
private Image dbImage;
private Graphics dbg;
Adapter ma = new Adapter();

public static void main(String args[]){
    JFrame frame = new MoveOval();
    frame.setSize(600,600); 
    frame.setVisible(true);
}

public MoveOval(){
    super("Move Oval");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    addMouseListener(ma);
    addMouseMotionListener(ma);

}
private class Adapter extends MouseAdapter{
    public void mousePressed(MouseEvent e){
        if(node.contains(e.getPoint())){
            preX = node.getBounds().x-e.getX();
            preY = node.getBounds().y-e.getX();
            offset = new Point(preX, preY);
        }
    }
    public void mouseDragged(MouseEvent e){
        if(node.contains(e.getPoint())){
            updateLocation(e);
        }
    }
    public void mouseReleased(MouseEvent e) {
           offset=null;
      }

}

public void updateLocation(MouseEvent e){
    Point to = e.getPoint();
    to.x += offset.x;
    to.y += offset.y;

    Rectangle bounds = node.getBounds();
    bounds.setLocation(to);
    node.setFrame(bounds);

    repaint();
}

public void paint(Graphics g){
    dbImage=createImage(getWidth(), getHeight());
    dbg = dbImage.getGraphics();
    paintComponent(dbg);
    g.drawImage(dbImage, 0, 0, this);
}
public void paintComponent(Graphics g){
    Graphics2D gd = (Graphics2D)g.create();
    gd.setColor(Color.blue);
    gd.fill(node);

    }
}

1 个答案:

答案 0 :(得分:3)

实际上是一个非常简单的错误并且易于修复。

public void mousePressed(MouseEvent e){
        if(node.contains(e.getPoint())){
            preX = node.getBounds().x-e.getX();
            preY = node.getBounds().y-e.getX(); // <- That's the bad guy.
            offset = new Point(preX, preY);
        }
    }

必须是-e.getY()而不是-e.getX()。