我正試圖創建一個程序,使用戶可以在空間中拖放橢圓。我能夠拖放,但在我嘗試在第二次運行後再次嘗試時,橢圓形跳至各個位置。我想知道有沒有人知道爲什麼會發生這種情況?我錯過了什麼嗎?謝謝使用鼠標拖動對象偵聽器
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);
}
}
如果您要創建併發布有效[mcve](請查看重要詳細信息的鏈接),效果會更好。此外,您不應該直接在JFrame的繪畫方法中繪製,因爲這需要麻煩,尤其是當您通過不調用任何超級方法來打破繪畫鏈時。 –