我在使用mouselistener时遇到问题。在过去的一个小时里,我一直在尝试解决此问题,并找到任何相关的教程,但是它们都是相同的,没有将其添加到jpanel中,但是我没有jpanel!
ClientApplicationWindow类:
public final void createClientWindow(int height, int width) {
ClientApplicationWindow clientApplicationWindow = new ClientApplicationWindow();
MouseEventHandler mouseEventHandler = new MouseEventHandler();
this.addMouseListener(mouseEventHandler);
frame.setTitle(Constants.CLIENT_NAME);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(clientApplicationWindow);
frame.setLocationRelativeTo(null);
frame.setFocusable(true);
frame.setResizable(false);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
}
});
loadIcon();
loadCursor();
frame.setVisible(true);
clientApplicationWindow.start();
}
MouseEventHandler类:
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse Clicked X: "+e.getX()+" - Mouse Clicked Y: "+e.getY());
}
谢谢!
最佳答案
没有更多的证据,这看起来很疲惫...
ClientApplicationWindow clientApplicationWindow = new ClientApplicationWindow();
MouseEventHandler mouseEventHandler = new MouseEventHandler();
this.addMouseListener(mouseEventHandler);
//...
frame.add(clientApplicationWindow);
假设
createClientWindow
实际上在ClientApplicationWindow
类之内,您正在创建ClientApplicationWindow
的新实例,将MouseListener
添加到当前实例(this
)并将新实例添加到框架中。这表明
this
未附加到可显示的容器,因此在屏幕上不可见...因此它无法接收鼠标事件...