我遇到了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());
}
谢谢!
答案 0 :(得分:3)
没有更多证据,这看起来很糟糕......
ClientApplicationWindow clientApplicationWindow = new ClientApplicationWindow();
MouseEventHandler mouseEventHandler = new MouseEventHandler();
this.addMouseListener(mouseEventHandler);
//...
frame.add(clientApplicationWindow);
假设createClientWindow
实际上在ClientApplicationWindow
类中,您正在创建ClientApplicationWindow
的新实例,并将MouseListener
添加到当前实例(this
})并将新实例添加到框架中......
这表明this
没有附加到可显示的容器上,因此在屏幕上看不到...所以它无法接收鼠标事件......