简体   繁体   中英

MouseListener doesn't work

i have some problems while trying to use the MouseListener. I've created a class called MouseManager that implements MouseListener and then i imported the MouseListener on the frame but when i click on the frame nothing happens. So here's the code of the MouseManager class:

public class MouseManager implements MouseListener {

@Override
public void mouseClicked(MouseEvent e) {
    int mx = e.getX();
    int my = e.getY();

    System.out.println("Clicked: " + mx + " " + my);

}

@Override
public void mouseEntered(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent e) {
    int mx = e.getX();
    int my = e.getY();

    System.out.println(mx + " " + my);

}

@Override
public void mouseReleased(MouseEvent e) {
    int mx = e.getX();
    int my = e.getY();

    System.out.println("Released: " + mx + " " + my);

}

}

and then here's the code that i use to implement the MouseManager class

MouseManager MouseMan = new MouseManager();
Window.frame.addMouseListener(MouseMan);

but as i sayed before nothing happens and the console shows no messages; i tryed to set the focusable of the window to false but it continues does not working. Sorry for my bad english.

you have to register the event in same class only ie your MouseManager Class by using

Frame objFrame = new Frame("MouseListener Demo");

objFrame.addMouseListener(this);

Here this refers to the instance of your current class. You will have to make the object of frame too as you are not extending the Frame Class directly.

And then just call make the object your work would be done.

You have to register for mouse events on blankArea and the panel. You should read here for more details.

Here is a part of what you have to do:

public class MouseManager implements MouseListener {
    Frame frame = new Frame();
    frame.addMouseListener(this); 
    ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM