简体   繁体   English

使用鼠标Listener拖动对象

[英]drag object using mouse Listener

I'm trying to create a program that able the user to drag and drop the oval around in the space. 我正在尝试创建一个程序,使用户能够在空间中拖放椭圆。 I was able to drag and drop but after I tried do it again on the second run, the oval jump all over the places. 我能够拖放但是在我第二次尝试再次尝试之后,椭圆形的跳跃遍布各个地方。 I was wondering if anyone know why this happen? 我想知道是否有人知道为什么会这样? Am i missing something? 我错过了什么吗? Thank you 谢谢

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);

    }
}

Actually a very simple mistake and easy to fix. 实际上是一个非常简单的错误,很容易修复。

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);
        }
    }

It has to be -e.getY() not -e.getX(). 它必须是-e.getY()而不是-e.getX()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM