簡體   English   中英

使用鼠標Listener拖動對象

[英]drag object using mouse Listener

我正在嘗試創建一個程序,使用戶能夠在空間中拖放橢圓。 我能夠拖放但是在我第二次嘗試再次嘗試之后,橢圓形的跳躍遍布各個地方。 我想知道是否有人知道為什么會這樣? 我錯過了什么嗎? 謝謝

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

    }
}

實際上是一個非常簡單的錯誤,很容易修復。

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()。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM