首页 > 解决方案 > 如何在不在类中实现的情况下添加 MouseMotionListener?

问题描述

我有一个测试即将到来,你必须记住 9 个小程序并编写它们。问题是,我有学习障碍,而且我无法正确记住事情——尤其是大事情,我经常会变得非常“模糊”。

该测试专门“以尽可能最小的方式编写这些程序”。

所以我不必冒着因雾而失败的风险——如何在不实现 MouseMotionListener 的情况下实现它?

我的老师提供的代码:

import javax.swing.JFrame; 
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;

public class One extends JFrame implements MouseMotionListener {
  public One() {
    this.setVisible(true); 
    this.setSize(400, 400); 
  }
  public void mouseMoved(MouseEvent e) {
    System.out.println("Mouse being moved...");  
  }
  public void mouseDragged(MouseEvent e) {
    int x = e.getX(), y = e.getY(); 
    System.out.println("(" + x + ", " + y + ")");  
  }  
  public static void main(String[] args) {
     One a = new One(); 
     a.addMouseMotionListener(a);
  }
}

具体来说,我不想担心编写自动实现的方法——因为我还有其他几个类似的问题——但是有更多空的实现方法。

标签: javaswing

解决方案


嗯。像这个?

public class One extends JFrame {

    public One() {
        setVisible(true);
        setSize(400, 400);

        addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) {
                System.out.println("Mouse being moved...");
            }
        });
    }

    public static void main(String[] args) {
        One a = new One();
    }
}

推荐阅读