在 JPanel 中实现 MouseMotionListener
Implementing MouseMotionListener in JPanel
从 继续,我在我的 JPanel
中实现了一个 MouseMotionListener
,这样我就可以跟踪鼠标事件以传递给其中包含的对象。
这没有用,所以我用 MouseMotionListener
实现了一个完全干净的 JPanel
(我的游戏面板有 none 的其他东西),但仍然没有工作。它只是在一个非常简单的 JFrame
中设置 FlowLayout
.
我是不是用错了?我应该如何触发鼠标事件?
JPanelMouseMotion
class:
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;
public class JPanelMouseMotion extends JPanel implements MouseMotionListener {
private static final long serialVersionUID = 1L;
public JPanelMouseMotion() {
super();
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
System.out.println(e.getX() + " / " + e.getY());
}
}
侦听器从未被调用,因为它从未被注册过。您应该致电 addMouseMotionListener
进行注册。
public class JPanelMouseMotion extends JPanel implements MouseMotionListener {
private static final long serialVersionUID = 1L;
public JPanelMouseMotion() {
super();
addMouseMotionListener(this); // register this JPanel as a Listener
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
System.out.println(e.getX() + " / " + e.getY());
}
}
从 JPanel
中实现了一个 MouseMotionListener
,这样我就可以跟踪鼠标事件以传递给其中包含的对象。
这没有用,所以我用 MouseMotionListener
实现了一个完全干净的 JPanel
(我的游戏面板有 none 的其他东西),但仍然没有工作。它只是在一个非常简单的 JFrame
中设置 FlowLayout
.
我是不是用错了?我应该如何触发鼠标事件?
JPanelMouseMotion
class:
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;
public class JPanelMouseMotion extends JPanel implements MouseMotionListener {
private static final long serialVersionUID = 1L;
public JPanelMouseMotion() {
super();
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
System.out.println(e.getX() + " / " + e.getY());
}
}
侦听器从未被调用,因为它从未被注册过。您应该致电 addMouseMotionListener
进行注册。
public class JPanelMouseMotion extends JPanel implements MouseMotionListener {
private static final long serialVersionUID = 1L;
public JPanelMouseMotion() {
super();
addMouseMotionListener(this); // register this JPanel as a Listener
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
System.out.println(e.getX() + " / " + e.getY());
}
}