文章目錄
- 滑鼠監聽器MouseListener
- 滑鼠監聽器MouseMotionListener
- 範例Java程式
- Java程式分析
滑鼠監聽器MouseListener
監聽滑鼠事件MouseEvent。
相應事件和處理方法
滑鼠事件 處理方法
MOUSE_CLICKED MouseClicked (MouseEvent) 滑鼠點擊(單或雙)
MOUSE_PRESSED MousePressed (MouseEvent) 滑鼠按下
MOUSE_RELEASED MouseReleased(MouseEvent) 滑鼠鬆開
MOUSE_ENTERED MouseEntered (MouseEvent) 滑鼠進入(某組件地區)
MOUSE_EXITED MouseExited (MouseEvent) 滑鼠離開(某組件地區)
滑鼠事件MouseEvent常用方法
int getClickCount() 得到點擊次數1 OR 2;
int getX(), int getY() 得到滑鼠的(象素)位置。
滑鼠監聽器MouseMotionListener
對於滑鼠的移動和拖放,另外用滑鼠運動監聽器MouseMotionListener。
因為許多程式不需要監聽滑鼠運動,把兩者分開可簡化程式。
相應事件和處理方法滑鼠事件 處理方法
MOUSE_MOVED MouseMoved (MouseEvent) 滑鼠在移動
MOUSE_DRAGGED MouseDragged(MouseEvent) 滑鼠被拖動
範例Java程式我們把對這兩個滑鼠監聽器綜合運用。
package com.test0803;import java.awt.Color;import java.awt.Frame;import java.awt.Label;import java.awt.TextField;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.event.MouseMotionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;public class Test_Mouse2 implements MouseMotionListener,MouseListener{Frame frame = new Frame("關於滑鼠的多重監聽器");TextField tField = new TextField(30);public Test_Mouse2(){Label label = new Label("請按下滑鼠左鍵並拖動");frame.add(label, "North");frame.add(tField, "South");frame.setBackground(new Color(180, 255, 255));frame.addMouseListener(this);frame.addMouseMotionListener(this);frame.addWindowListener(new WindowAdapter() {@Overridepublic void windowClosing(WindowEvent e) {// TODO Auto-generated method stubSystem.exit(0);}});frame.setSize(300, 200);frame.setLocation(400, 250);frame.setVisible(true);}public static void main(String[] args) {new Test_Mouse2();}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stubSystem.out.print("滑鼠點擊----" + "\t");if (e.getClickCount()==1) {System.out.println("單擊!");} else if (e.getClickCount()==2) {System.out.println("雙擊!");} else if (e.getClickCount()==3) {System.out.println("三連擊!!");}}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stubSystem.out.println("滑鼠按下");}@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stubSystem.out.println("滑鼠鬆開");}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stubtField.setText("滑鼠已經進入表單");}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stubtField.setText("滑鼠已經移出表單");}@Overridepublic void mouseDragged(MouseEvent e) {// TODO Auto-generated method stubString string = "滑鼠拖動到位置:(" + e.getX() + "," + e.getY() +")";tField.setText(string);}@Overridepublic void mouseMoved(MouseEvent e) {// TODO Auto-generated method stub}}
Java程式分析執行程式。通過執行結果,我們可以得到監聽器不同方法的含義。滑鼠未進入表單時滑鼠進入表單時在表單內拖動滑鼠同時輸出:
滑鼠按下滑鼠鬆開
在表單內單擊滑鼠輸出:
滑鼠按下滑鼠鬆開滑鼠點擊----單擊!
由此可知監聽器內部的執行順序。
在表單內雙擊滑鼠輸出:
滑鼠按下滑鼠鬆開滑鼠點擊----單擊!滑鼠按下滑鼠鬆開滑鼠點擊----雙擊!
在表單內三連擊滑鼠輸出:
滑鼠按下滑鼠鬆開滑鼠點擊----單擊!滑鼠按下滑鼠鬆開滑鼠點擊----雙擊!滑鼠按下滑鼠鬆開滑鼠點擊----三連擊!!