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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With