Java MouseListener [英] Java MouseListener

查看:101
本文介绍了Java MouseListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆JLabel,我想捕获鼠标点击事件。目前我不得不使用:

I have a bunch of JLabels and i would like to trap mouse click events. at the moment i am having to use:

public void mouseClicked(MouseEvent arg0) {

}

public void mouseExited(MouseEvent arg0) {

}

public void mouseEntered(MouseEvent arg0) {

}

public void mousePressed(MouseEvent arg0) {

}

public void mouseReleased(MouseEvent arg0) {

    System.out.println("Welcome to Java Programming!"); 
}

我想知道是否有更简洁的方法来做这个而不是一堆我不想陷阱的事件?

I was wondering if there is a tidier way of doing this instead of having a bunch of events I do not wish trap?

编辑:

    class MyAdapter extends MouseAdapter {
    public void mouseClicked(MouseEvent event) {

        System.out.println(event.getComponent());
    }
}

上述工作,但netBeans说添加@override anotation。这意味着什么?

the above works but netBeans says add @override anotation. what does this mean?

编辑:好的。固定并解决。

ok got it. fixed and solved.

推荐答案

使用 MouseAdapter()

用于接收鼠标事件的抽象适配器类。此类中的方法为空。此类用于创建侦听器对象。
所以你需要只实现你喜欢的方法,如下面的例子:

An abstract adapter class for receiving mouse events. The methods in this class are empty. This class exists as convenience for creating listener objects. So you need to implement only the method you like such as following example:

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class MainClass extends JPanel {

  public MainClass() {

      addMouseListener(new MouseAdapter() { 
          public void mousePressed(MouseEvent me) { 
            System.out.println(me); 
          } 
        }); 

  }

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.getContentPane().add(new MainClass());

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setSize(200, 200);
    frame.setVisible(true);
  }
}

这篇关于Java MouseListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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