Java MouseListener

iTEgg picture iTEgg · Apr 19, 2010 · Viewed 100k times · Source

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?

EDIT:

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

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

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

EDIT: ok got it. fixed and solved.

Answer

ring bearer picture ring bearer · Apr 19, 2010

Use 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);
  }
}