2013-03-24 48 views
0

我試圖在繪畫部分獲得光標的點,並只畫一個橢圓。雖然沒有運氣!小程序繪畫

public void paint(Graphics g){ 
    Point ComponentPoint = PaintPanel.getLocationOnScreen(); 
    Point CursorPoint= MouseInfo.getPointerInfo().getLocation(); //gets cursor point 

    int ComPX = ComponentPoint.x; 
    int ComPY = ComponentPoint.y; 
    int CurPX = CursorPoint.x; 
    int CurPY = CursorPoint.y; 
    int FinalX = CurPX - ComPX; 
    int FinalY = CurPY - ComPY; 
    g.drawOval(FinalX, FinalY, 20, 20); 
} 

private void PaintPanelMouseDragged(java.awt.event.MouseEvent evt) {           
    //when mouse is moved over paintpanel 

    //PaintPanel.repaint(); 
    not working 
}    

這是不需塗漆方法,圖像:

http://i.stack.imgur.com/VOyhr.png

+0

考慮創建併發佈一個小的*幾乎*工作的例子,你最好的嘗試解決方案,換句話說,[sscce](http://sscce.org)。 – 2013-03-24 00:51:20

+0

隨着我發佈它沒有顯示任何東西:/我嘗試了別的東西,它擺脫了一切,但畫了橢圓形。 – bob 2013-03-24 00:57:21

+0

很難知道如何在沒有上下文的情況下發布一小段代碼。這就是爲什麼我要求你通過創建一個非常小但可編譯和可運行的程序來提供一些上下文。 – 2013-03-24 00:59:11

回答

1

在這樣的paint方法不能添加代碼。 YOu不會在paint方法中引用MouseInfo類,因爲您無法控制何時調用paint()方法。您應該使用MouseListener和MouseMotionListner進行自定義繪畫。另外,自定義繪畫不應該在繪畫方法中完成。

請參閱Custom Painting Approaches兩種解決方案。

+0

和[如何編寫鼠標監聽器](http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html) – MadProgrammer 2013-03-24 01:31:40