事件侦听器和鼠标监听器 [英] Event listeners and Mouse listeners

查看:271
本文介绍了事件侦听器和鼠标监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有可能来检查的JButton被双击使用事件侦听器,而不是一个鼠标监听器。请看下面的code;

I was wondering if it is possible to check if a JButton is double clicked using an event Listener instead of a mouse listener. Consider the following code;

public void actionPerformed(ActionEvent arg0){
    if (arg0.getClickCount() == 2){
        System.out.println("You Doubled clicked");
    }
}

我得到一个错误说 getClickCount()是未定义的类型的ActionEvent 。是鼠标不也被认为是事件的点击或DoubleClick?思考。

I get an error saying getClickCount() is undefined for the type ActionEvent. Is the click or doubleclick of a mouse not also considered as an event? Thoughts.

推荐答案

您想使用 MouseAdapter 。它允许你不会堆积在code。与不必要的方法(的mouseDragged 的mouseEntered 等)。

You want to use a MouseAdapter. It permits you to don't clutter your code with unecessary methods (mouseDragged, mouseEntered etc).

public class MyClass extends MouseAdapter {
    @Override
    public void mouseClicked(MouseEvent e) {
        if (e.getClickCount() == 2) {
            // Double click
        } else {
           // Simple click
        }
    }     
}

另外,如果你的类已经扩展了另一个类,试试这个code:

Alternatively, if your class already extends another class, try this code:

public class MyClass extends MyBaseClass {
    private MouseAdapter ma;

    public MyClass () {
        final MyClass that = this;
        ma = new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                that.myMouseClickedHandler(e);
            }
        };
    }

    public void myMouseClickedHandler(MouseEvent e) {
        if (e.getClickCount() == 2) {
            // Double click
        } else {
           // Simple click
        }        
    }
 }

这篇关于事件侦听器和鼠标监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆