Why cant i do addMouseListener(e ->{ });?
Asked Answered
P

1

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

Publicize answered 18/4, 2018 at 8:36 Comment(2)
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 useBismuth
MouseListener is not a functional interface (because it has more than one abstract method). So you cannot implement it with a lambda function.Hendrika
B
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

Bismuth answered 18/4, 2018 at 8:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.