public class Demo extends JFrame { private JTextArea textArea; public Demo() { setBounds(100, 100, 470, 300); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container c = getContentPane(); c.setLayout(null); JLabel label1 = new JLabel("鼠标事件区域"); label1.setBounds(284, 37, 160, 20); c.add(label1); JLabel label = new JLabel(); label.setBounds(244, 57, 160, 141); label.setBorder(BorderFactory.createLineBorder(Color.RED)); c.add(label); textArea = new JTextArea();//创建文本域 JScrollPane scrollPane = new JScrollPane(textArea);//滚动面板 scrollPane.setBounds(20, 30, 190, 190); c.add(scrollPane); label.addMouseListener(new MyMouseEvent());//调用自定义方法类 setVisible(true); } //在MyMouseEvent上,Alt+Ins,快速创建方法。 class MyMouseEvent implements MouseListener { @Override public void mouseClicked(MouseEvent e) { int btn = e.getButton();//获取鼠标按键 switch (btn) { case MouseEvent.BUTTON1: textArea.append("鼠标左键被点击 "); break; case MouseEvent.BUTTON2: textArea.append("鼠标滚轮被点击 "); break; case MouseEvent.BUTTON3: textArea.append("鼠标右键被点击 "); break; } int count = e.getClickCount(); textArea.append("鼠标被点击了" + count + "次 "); } public void mousePressed(MouseEvent e) { textArea.append("鼠标被按下 "); } public void mouseReleased(MouseEvent e) { textArea.append("鼠标被释放 "); } public void mouseEntered(MouseEvent e) { textArea.append("鼠标进入区域 "); } public void mouseExited(MouseEvent e) { textArea.append("鼠标离开区域 "); } } public static void main(String[] args) { new Demo(); } }