2015-10-15 46 views
0

首先,這裏是相關的代碼:的MouseMotionListener顯示(X,Y)偏移

canvas = new CanvasPanel(); 
    canvas.setBackground(Color.white); 
    canvas.addMouseListener(new PointListener()); 
    canvas.addMouseMotionListener(new PointListener()); 

    JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, canvas); 


class CanvasPanel extends JPanel 
{ 
    public void paintComponent(Graphics page) 
    { 
     super.paintComponent(page); 

     if (mouseDragged == true) 
     { 
      page.drawRect(x1, y1, x3, y3); 
      canvas.repaint(); 
     } 
    } 
} 


class PointListener implements MouseListener, MouseMotionListener 
{ 
    public void mousePressed (MouseEvent event) 
    { 
     mouseDragged = true; 
     x1 = event.getX(); 
     y1 = event.getY(); 
    } 
    public void mouseReleased (MouseEvent event) 
    { 
     // some code 
    } 

    public void mouseDragged(MouseEvent event) 
    { 
     x3 = event.getX(); 
     y3 = event.getY(); 
     canvas.repaint(); 
    } 

那麼這段代碼做的是,當我點擊畫布組件,它將繪製的輪廓矩形和大小隨着我拖動鼠標而變化

但是,當我單擊並開始拖動鼠標時,矩形右下角有一個偏移量。它似乎跳到一個更大的尺寸第二我拖動鼠標。有趣的是,更接近我點擊的畫布組件的左上角,矩形大小越接近我用鼠標繪製的矩形。

我該如何解決這個問題?

回答

1

記住,drawRect使用xywidthheight,因爲它的參數,你實際上應使用點擊點和拖動點

也許像之間的增量...

public void paintComponent(Graphics page) 
{ 
    super.paintComponent(page); 

    if (mouseDragged == true) 
    { 
     int x = Math.min(x1, x3); 
     int y = Math.min(y1, y3); 
     int width = Math.max(x1, x3) - x; 
     int height = Math.max(y1, y3) - y; 
     page.drawRect(x, y, width, height); 
    } 
} 

而且,請不要在paint方法中調用repaint方法

+0

Oh duh:/。謝謝你,我知道這是愚蠢的 – ASchmalzWorld

+0

答案可能並不明顯,但'drawRect'不接受負值的寬度/高度值;) – MadProgrammer

相關問題