假設想對一個鼠標的操作進行監聽,假設鼠標按下、松開等。則能夠使用MouseListener接口。
package com.beyole.util;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
class MyMouseHandle extends JFrame implements MouseListener {
private JTextArea text = new JTextArea();
public MyMouseHandle() {
super.setTitle("Crystal");// 設置標題
JScrollPane pane = new JScrollPane(text);// 增加滾動欄
pane.setBounds(5, 5, 300, 200);// 設置絕對位置
super.add(pane);// 向窗口中增加組件
text.addMouseListener(this);// 增加mouse監聽
super.setSize(310, 210);
super.setVisible(true);
super.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent arg0) {
System.exit(1);
}
});
}
public void mouseClicked(MouseEvent e)// 鼠標單擊事件
{
int c = e.getButton();// 得到按下的鼠標鍵
String mouseInfo = null;// 接收信息
if (c == MouseEvent.BUTTON1)// 推斷是鼠標左鍵按下
{
mouseInfo = "左鍵";
} else if (c == MouseEvent.BUTTON3) {// 推斷是鼠標右鍵按下
mouseInfo = "右鍵";
} else {
mouseInfo = "滾軸";
}
text.append("鼠標單擊:" + mouseInfo + ".\n");
}
public void mouseEntered(MouseEvent e)// 鼠標進入組件
{
text.append("鼠標進入組件.\n");
}
public void mouseExited(MouseEvent e)// 鼠標退出組件
{
text.append("鼠標退出組件.\n");
}
public void mousePressed(MouseEvent e)// 鼠標按下
{
text.append("鼠標按下.\n");
}
public void mouseReleased(MouseEvent e)// 鼠標松開
{
text.append("鼠標松開.\n");
}
}
public class MyMouseEventDemo {
public static void main(String[] args) {
new MyMouseHandle();
}
}
程序截圖:
