Search code examples
javamouseevent

"mousePressed/mouseClicked" is not working for any reason


So basically , I'm doing an arkanoid , and I want that when I click in my programm, an action starts.

This is my code so far:

canvas.addMouseMotionListener(new MouseAdapter() {
        
        public void mousePressed(MouseEvent e) {
            super.mousePressed(e);
            player.mousePressed(e);
        }
        
        @Override
        public void mouseMoved(MouseEvent e) {
            super.mouseMoved(e);
            player.mover(e.getX());
        }   
        
        
        
    });
    

The mouseMoved is working.

Player.mousePressed =

public void mousePressed(MouseEvent e) {
    this.setSpace(true);
    switch (e.getButton()) {
        case MouseEvent.BUTTON1 : space = true; break;
    }
    //This is only for test 
    System.out.println(e.getButton());
    if (this.isSpace() == true) {
        //This is only for test 
        System.out.println("test");
    }
}

If this should works, it should send me two syso but it doesnt send it. I also tried it with MouseClicked but it also doesnt work.


Solution

  • canvas.addMouseMotionListener(new MouseAdapter() {
        
        public void mousePressed(MouseEvent e) {
    

    Component.addMouseMotionListener is declared as:

    public void addMouseMotionListener​(MouseMotionListener l)
    

    MouseMotionListener extends EventListener and adds the methods mouseDragged and mouseMoved but not mousePressed.

    So you want to addMouseListener as well as addMouseMotionListener​. MouseAdapter implementing two distinct interfaces has done you in.