实现MouseListener与addMouseListener

时间:2016-01-08 16:24:55

标签: java events mouseevent mouselistener

胡家伙,

我有一个奇怪的行为,实现了MouseListener接口和addMouseListener。 这是我的代码:

public class SwitchButton extends JPanel {
    public static final Dimension PREF_SIZE = new Dimension(32, 16);
    private SwitchButtonModel switchButton;

    public SwitchButton() {
       this.setBorder(BorderFactory.createEmptyBorder(0, 0, (int)PREF_SIZE.getWidth(), (int)PREF_SIZE.getHeight()));
       switchButton = new SwitchButtonModel();
       addMouseListener(new MouseAdapter() {
           @Override
           public void mouseClicked(MouseEvent e) {
               switchButton.toggleStatus();
           }
       });
    }

此代码有效。当我单击面板区域时,将执行switchButton的toggleStatus()方法。

如果我实现了MouseListener接口,则永远不会调用事件mouseClicked。

public class SwitchButton extends JPanel implements MouseListener {
    public static final Dimension PREF_SIZE = new Dimension(32, 16);
    private SwitchButtonModel switchButton;

    public SwitchButton() {
        this.setBorder(BorderFactory.createEmptyBorder(0, 0, (int)PREF_SIZE.getWidth(), (int)PREF_SIZE.getHeight()));
        switchButton = new SwitchButtonModel();

        @Override
        public void mouseClicked(MouseEvent arg0) {
            switchButton.toggleStatus();

        }
... All other methods of MouseListener interface ...

为什么呢?你能帮助我吗? 谢谢!

0 个答案:

没有答案