MouseListener 方法接口中的mouseClicked() 方法和mousePressed() 方法有什麼區別
這是一個熱門的話題,讓我們來深入的找尋答案,Java’s AWT 庫提供了兩個接口來監聽和接收鼠標事件. 一個是 java.awt.event.MouseListener:
public interface MouseListener extends EventListener
{
public void mousePressed(MouseEvent e);
public void mouseReleased(MouseEvent e);
public void mouseClicked(MouseEvent e);
public void mouseEntered(MouseEvent e);
public void mouseExited(MouseEvent e);
}
另一個是 java.awt.event.MouseMotionListener:
public interface MouseMotionListener extends EventListener
{
public void mouseDragged(MouseEvent e);
public void mouseMoved(MouseEvent e);
}
Swing 提供了 MouseInputListener, 這個接口的同時擴展了MouseMotionListener 和MouseListener 接口.
mousePressed() 當用戶按下鼠標按鈕時發生.
mouseReleased() 當用戶松開鼠標按鈕時發生.
mouseClicked() 當用戶按下並松開鼠標按鈕時發生. 用戶在選擇或雙擊圖標的時候通常會點擊鼠標按鈕. 用戶如果在松開鼠標之前移動鼠標,點擊不會導致鼠標相應事件出現.
因為點擊鼠標是按下鼠標和松開鼠標的結合, 在事件分配給 mouseClicked() 方法之前, mousePressed() 和 mouseReleased() 方法已同時被調用.
mouseEntered() 當鼠標離開當前組件並進入你所監聽的組件時激活事件.
mouseExited() 當鼠標離開你所監聽的組件時發生.
mouseDragged() 當用戶按下鼠標按鈕並在松開之前進行移動時發生.在mouseDragged() 後松開鼠標不會導致mouseClicked().
mouseMoved() 當鼠標在組件上移動而 不時拖動時發生.
要監聽鼠標事件就必須調用這些接口之一,或擴展一個鼠標適配器(mouse adapters) 類. AWT 提供了兩種監聽適配器(listener adapters): java.awt.event.MouseAdapter 和java.awt.event.MouseMotionAdapter.
Swing 為MouseInputListener提供了一個叫做javax.swing.event.MouseInputAdapter的適配器. 有了適配器你就不必調用接口中每個方法了. 取而代之, 你只需簡單的擴展適配器並重寫你要監聽的方法就可以了.
如果你還是很迷惑, 再看看API 並寫個小測試程序. 有時嘗試理解不同事件的最好方法different events. 我寫了一個小小的應用程序來表現兩種鼠標事件的區別.這裡是完整的代碼:
import java.awt.*;
import java.awt.event.*;
public class MouseTest extends Frame
{
public MouseTest()
{
Button b = new Button("JavaWorld JavaQ&A");
b.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
);
add(b,BorderLayout.NORTH);
addMouseListener(new MouseTest.MouseHandler());
addMouseMotionListener(new MouseTest.MouseMotionHandler());
}
// MouseHandler is an inner class that implements the MouseListener.
// Each method simply prints out a message to the command line.
private class MouseHandler implements MouseListener
{
public void mousePressed(MouseEvent e)
{
System.out.println("mouse pressed");
}
public void mouseClicked(MouseEvent e)
{
System.out.println("moused clicked");
}
public void mouseReleased(MouseEvent e)
{
System.out.println("mouse released");
}
public void mouseEntered(MouseEvent e)
{
System.out.println("mouse entered");
}
public void mouseExited(MouseEvent e)
{
System.out.println("mouse exited");
}
}
// MouseMotionHandler is an inner class that implements the MouseMotionListener.
// Each method simply prints out a message to the command line.
private class MouseMotionHandler implements MouseMotionListener
{
public void mouseMoved(MouseEvent e)
{
System.out.println("mouse moved");
}
public void mouseDragged(MouseEvent e)
{
System.out.println("mouse dragged");
}
}
public static void main(String[] args)
{
new MouseTest().show();
}
}
象上邊那樣寫一個小小的測試程序是對陌生的API 進行試驗的好方法.