2016-03-04 38 views
1

我正試圖創建一個程序,使用戶可以在空間中拖放橢圓。我能夠拖放,但在我嘗試在第二次運行後再次嘗試時,橢圓形跳至各個位置。我想知道有沒有人知道爲什麼會發生這種情況?我錯過了什麼嗎?謝謝使用鼠標拖動對象偵聽器

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

    } 
} 
+0

如果您要創建併發布有效[mcve](請查看重要詳細信息的鏈接),效果會更好。此外,您不應該直接在JFrame的繪畫方法中繪製,因爲這需要麻煩,尤其是當您通過不調用任何超級方法來打破繪畫鏈時。 –

回答

2

其實很簡單的一個錯誤,很容易修復。

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

+0

謝謝你!我不敢相信我沒有看到。 :) –

+1

這種事情偶爾也會發生在我身上,當我真的很累的時候。有時候,這是你錯過的簡單錯誤。無論如何,如果您將此標記爲正確答案,我將不勝感激。 – Mark

+0

@HuyTrinh:你會想要接受和提高Mark的答案。有關詳情,請從幫助網站閱讀本節:[某人回答](http://stackoverflow.com/help/someone-answers)。但請注意,您仍然不應該在JFrame中繪製,而應該在JPanel的paintComponent方法中繪製,並且仍然應該記得調用super的繪畫方法。 1+這個答案。 –