5

I currently am using this code here for my mouse listener:

    public void mousePressed(MouseEvent e) {

JLabel labelReference=(JLabel)e.getSource();
    if(labelReference.getBackground()==HighLight) {
    turn^=true;
    if(turn==true){
       labelReference.setBackground(Color.blue);
       }; 
       if(turn==false){
           labelReference.setBackground(Color.red); 
           };
      }     
}

This works but i am trying to change /remove that for when adding my Mouse listener to all JLabels:

Pjaser[i][j].addMouseListener(e ->{

            });

But seems to give me an error, this seems to work fine when its a addActionListener( e->{ Could someone give me any tips on fixing this

Thanks

daniu
  • 14,137
  • 4
  • 32
  • 53
  • 7
    Because `MouseListener` doesn't have one method, it has several. You can, however, use `MouseAdapter`, which implements (with blank implementations) all the methods of `MouseListener` (and `MouseMotionListener`) so you can choose the ones you want use – MadProgrammer Apr 18 '18 at 08:38
  • 2
    `MouseListener` is not a functional interface (because it has more than one abstract method). So you cannot implement it with a lambda function. – khelwood Apr 18 '18 at 08:42

1 Answers1

7

So, let's take a look at ActionListener and MouseListener...

public interface ActionListener extends EventListener {
    /**
     * Invoked when an action occurs.
     */
    public void actionPerformed(ActionEvent e);

}

public interface MouseListener extends EventListener {

    /**
     * Invoked when the mouse button has been clicked (pressed
     * and released) on a component.
     */
    public void mouseClicked(MouseEvent e);

    /**
     * Invoked when a mouse button has been pressed on a component.
     */
    public void mousePressed(MouseEvent e);

    /**
     * Invoked when a mouse button has been released on a component.
     */
    public void mouseReleased(MouseEvent e);

    /**
     * Invoked when the mouse enters a component.
     */
    public void mouseEntered(MouseEvent e);

    /**
     * Invoked when the mouse exits a component.
     */
    public void mouseExited(MouseEvent e);
}

Okay, so ActionListener has only one possible method, where as MouseListener has 5, so when you do...

Pjaser[i][j].addMouseListener(e ->{

});

Which method is Java suppose to call?

Lucky for you (and the rest of us), the Java developers also felt the same way, they didn't want to have ti implement ALL the methods of MouseListener (or MouseMotionListener or MouseWheelListener), so they provided a "default" implementation of all of them, which basically just creates empty implementations of the methods, MouseAdapter...

Pjaser[i][j].addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
    }
});

Okay, it's not "exactly" the same, but it's a darn sight easier to read and manage

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366