2012-11-02 271 views
0

我在程序中遇到了鼠標事件問題。我試圖用畫布編寫一個繪圖程序。如何在Java中按下鼠標按鈕時收聽鼠標移動事件

如果用戶左鍵單擊並移動鼠標,應繪製圖形。所以我在其中定義了Drawer類,其中boolean allow_draw,並且我添加了一個方法draw

draw被稱爲在畫布mousemoved事件和allow_draw設置真假與mousepressedreleased

然而,mousemoved不點火,而我按下鼠標按鈕...

我的問題是:我怎麼能聽鼠標動作,同時按下鼠標鍵。

希望你知道我在找什麼:)

回答

2

你可不可以發佈你的源代碼?請嘗試添加一個MouseMotionListener。以下是我正在開發的一個項目的一個例子。

addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { 

     public void mouseDragged(java.awt.event.MouseEvent evt) { 
      formMouseDragged(evt); 
     } 
     public void mouseMoved(java.awt.event.MouseEvent evt) { 
      formMouseMoved(evt); 
     } 
    });` 
+0

我不清楚爲什麼您需要'allow_draw'標誌,但請注意,請確保您正確同步allow_draw。否則,您將遇到該變量貨幣的問題。 – RWVan3

+0

謝謝,現在它工作! :) 我寫在我的主要和設計器類的構造函數 ' public CanvasTest(){ initComponents(); this.drw =新的抽屜(this); this.canvas.addMouseMotionListener(new MouseMotionListener(this)); this.canvas.addMouseListener(new MouseClickListener(this)); //this.canvas.addMouseMotionListener(new MouseMotion(this)); } ' – user1795687

+0

抱歉,codehighlighting不會對我工作...但我做你:) – user1795687

0

鼠標移動事件與按下按鈕將是一個拖動事件。只需聽'MouseListener#mouseDragged',這就是你要找的。使用的MouseListener和MouseMotionListener和,這是在MouseAdapter類方便地組合的組合

1

你應該考慮,

  • 當mousePressed發生時,在上轉動繪圖
  • 打開繪圖關閉時如果的mouseReleased圖是上(使用IF塊)發生內的mouseDragged
  • 繪圖。
  • 使用addMouseListener(...)方法和addMouseMotionListener(...)方法將您的MouseAdapter對象兩次添加到組件。
相關問題