这让我发疯了。这一定是一个非常简单的问题,但我不可能看到它。
基本上 mouseMoved 永远不会被调用。下面是代码。
public class MouseMotionThing {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame jFrame = new JFrame();
jFrame.setContentPane(new ContentPane());
jFrame.setSize(400, 400);
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
}
还有我的面板。此实现使用 MouseInputListener:
class ContentPane extends JPanel implements MouseInputListener {
int x = 0, y = 0;
public ContentPane() {
setOpaque(true);
addMouseListener(this);
addMouseMotionListener(this);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(0, 0, x, y);
}
@Override
public void mouseDragged(MouseEvent e) {
System.out.println("Mouse Dragged!");
}
@Override
public void mouseMoved(MouseEvent e) {
System.out.println("CALLED MOUSE MOVED");
x = e.getX();
y = e.getY();
repaint();
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
而此替代实现仅使用 MouseMotionListener:
class ContentPane extends JPanel implements MouseMotionListener {
int x = 0, y = 0;
public ContentPane() {
setOpaque(true);
addMouseMotionListener(this);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(0, 0, x, y);
}
@Override
public void mouseDragged(MouseEvent e) {
System.out.println("Mouse Dragged!");
}
@Override
public void mouseMoved(MouseEvent e) {
System.out.println("CALLED MOUSE MOVED");
x = e.getX();
y = e.getY();
repaint();
}
}
在上述替代实现中,都没有调用 mouseMoved。我每次都在添加正确的听众,但它根本不起作用。mouseDragged 工作正常。我错过了什么?
LE:我在 Ubuntu 12.10 和 JDK 7 上测试了代码,运行良好。然后当我回到我的 W8 机器时,它开始工作了。我只是重新启动笔记本电脑。我无法重现该问题,也无法追踪它,但如果我再次遇到它并设法找到一些东西,我会回来的。