简体   繁体   English

MouseListener不起作用

[英]MouseListener doesn't work

i have some problems while trying to use the MouseListener. 我在尝试使用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. 我创建了一个名为MouseManager的类,该类实现了MouseListener,然后将MouseListener导入了框架,但是当我单击框架时,什么也没有发生。 So here's the code of the MouseManager class: 因此,这是MouseManager类的代码:

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类的代码

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. 我试图将窗口的可聚焦性设置为false,但它继续无法正常工作。 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. 然后只需调用make该对象即可完成工作。

You have to register for mouse events on blankArea and the panel. 您必须在blankArea和面板上注册鼠标事件。 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); 
    ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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