假設想對一個鼠標的操做進行監聽,假設鼠標按下、鬆開等。則可以使用MouseListener接口。java
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(); } }