JAVA:事件監聽器之鼠標監聽


addMouseListener

public void addMouseListener(MouseListener l)

添加指定的鼠標偵聽器,以接收發自此組件的鼠標事件。如果偵聽器 lnull,則不會拋出異常並且不執行動作。 

java.awt.event
接口 MouseListener

用於接收組件上“感興趣”的鼠標事件(按下、釋放、單擊、進入或離開)的偵聽器接口。(要跟蹤鼠標移動和鼠標拖動,請使用 MouseMotionListener。)

旨在處理鼠標事件的類要么實現此接口(及其包含的所有方法),要么擴展抽象類 MouseAdapter(僅重寫所需的方法)

然后使用組件的 addMouseListener 方法將從該類所創建的偵聽器對象向該組件注冊。當按下、釋放或單擊(按下並釋放)鼠標時會生成鼠標事件。鼠標光標進入或離開組件時也會生成鼠標事件。發生鼠標事件時,將調用該偵聽器對象中的相應方法,並將 MouseEvent 傳遞給該方法。                                  

 

方法摘要
void mouseClicked(MouseEvent e)
鼠標按鍵在組件上單擊(按下並釋放)時調用。
void mouseEntered(MouseEvent e)
鼠標進入到組件上時調用。
void mouseExited(MouseEvent e)
鼠標離開組件時調用。
void mousePressed(MouseEvent e)
鼠標按鍵在組件上按下時調用。
void mouseReleased(MouseEvent e)
鼠標按鈕在組件上釋放時調用。

 ——摘自:JDK6API

 

例子:

 1 import javax.swing.*;
 2 import java.awt.*;
 3 import java.awt.event.*;
 4 public class MouseDemo
 5 {
 6     //定義該圖形中所需的組件的引用
 7     private Frame f;
 8     private Button bt; 
 9     
10     //方法
11    MouseDemo()//構造方法
12     {
13         madeFrame();
14     }
15     
16     public void madeFrame()
17     {
18         f = new Frame("My Frame");
19         
20         //對Frame進行基本設置。
21         f.setBounds(300,100,600,500);//對框架的位置和大小進行設置
22         f.setLayout(new FlowLayout(FlowLayout.CENTER,5,5));//設計布局
23         
24         bt = new Button("My Button");
25         
26         //將組件添加到Frame中
27         f.add(bt);
28         
29         //加載一下窗體上的事件
30         myEvent();
31         
32         //顯示窗體
33         f.setVisible(true);
34     }
35     
36     private void myEvent()
37     {
38         f.addWindowListener(new WindowAdapter()//窗口監聽
39         {
40             public void windowClosing(WindowEvent e)
41             {
42                 System.out.println("窗體執行關閉!");
43                 System.exit(0);
44             }
45         });
46 
47         bt.addActionListener(new ActionListener()//按鈕監聽
48         {
49             public void actionPerformed(ActionEvent e)
50             {
51                  System.out.println("按鈕活動了!");
52             }
53         });
54         bt.addMouseListener(new MouseAdapter()//鼠標監聽
55         {
56             private int count = 1; 
57             private int mouseCount = 1;
58             public void mouseEntered(MouseEvent e)
59             {
60                 System.out.println("鼠標監聽"+count++);
61             }
62             public void mouseClicked(MouseEvent e)
63             {
64                 if(e.getClickCount()==2)
65                    System.out.println("鼠標被雙擊了");
66                 else System.out.println("鼠標被點擊"+mouseCount++);
67             }
68         });
69     }
70     
71     public static void main(String[] agrs)
72     {
73         new MouseDemo();
74     }
75 }

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM