鼠标监听事件MouseListener

复制代码
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("鼠标左键被点击\n");
                    break;
                case MouseEvent.BUTTON2:
                    textArea.append("鼠标滚轮被点击\n");
                    break;
                case MouseEvent.BUTTON3:
                    textArea.append("鼠标右键被点击\n");
                    break;
            }
            int count = e.getClickCount();
            textArea.append("鼠标被点击了" + count + "次\n");
        }

        public void mousePressed(MouseEvent e) {
            textArea.append("鼠标被按下\n");
        }

        public void mouseReleased(MouseEvent e) {
            textArea.append("鼠标被释放\n");
        }

        public void mouseEntered(MouseEvent e) {
            textArea.append("鼠标进入区域\n");
        }

        public void mouseExited(MouseEvent e) {
            textArea.append("鼠标离开区域\n");
        }
    }

    public static void main(String[] args) {
        new Demo();
    }
}
复制代码

 

posted @   夕西行  阅读(5800)  评论(1编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· Open-Sora 2.0 重磅开源!
点击右上角即可分享
微信分享提示