Reputation:
In the game that I'm currently making I have three different mousePressed
methods, one for single fire, one for automatic fire and one for melee attacks. Because the one for automatic fire uses a swing Timer
I can override it in the other mousePressed
methods by using timer.stop();
in them.
But the single fire mousePressed
calls the fire()
method directly so I can't override it in any way from the other mousePressed
. The code below shows the method for the fireing (bullet is a ArrayList
).
public void fire(){
if(!power.getChainsaw()){
bullet.add(new Bullet(x, y));
}
}
When the player gets a melee weapon I therefor need to remove the MouseListener
for the single fireing. I have tried the code below but it didn't work.
removeMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
player.mousePressed2(e);
}
)};
I add the single fire and melee MouseListener
in the exact same way as this. This is hwo the acctual mousePressed
methods lok like.
public void mousePressed2(MouseEvent e){
if(SwingUtilities.isLeftMouseButton(e)){
timer.stop();
fire();
}
}
public void mousePressed3(MouseEvent e){
if(SwingUtilities.isLeftMouseButton(e)){
timer.stop();
}
}
mousePressed2
is the single fire method and mousePressed3
is the melee method
Upvotes: 0
Views: 1850
Reputation: 28511
removeMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
player.mousePressed2(e);
}
)};
Look at what you are doing here. You are removing an instance of MouseAdapter
created in place. This means that a new instance of mouse adapter will be created and then removed, but because the specific listener instance is not binded to any button, nothing will happen.
Pass the correct listener to the removeMouseListener
method and it will work.
MouseAdapter myListener = new MouseAdapter() {
public void mousePressed(MouseEvent e){
player.mousePressed2(e);
}
};
someButton.addMouseListener(myListener);
// then when you want to remove it, use the same referenece.
someButton.removeMouseListener(myListener);
Upvotes: 1