在JPanel

时间:2015-10-02 13:25:37

标签: java swing jpanel mouselistener mousemotionlistener

this question继续,我在我的MouseMotionListener中实现JPanel,以便我可以跟踪鼠标事件以传递给其中包含的对象。

这没有用,所以我用JPanel实现了一个完全干净的MouseMotionListener(我的游戏面板没有其他东西),但仍然没有工作。它只是设置在一个非常简单的JFrame FlowLayout

我使用它错了吗?我打算如何触发鼠标事件?

JPanelMouseMotion上课:

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());
    }

}

1 个答案:

答案 0 :(得分:3)

永远不会调用侦听器,因为它从未注册过。您应该致电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());
    }

}