java - 如何在不在类中实现的情况下添加 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);
}
}
具体来说,我不想担心编写自动实现的方法——因为我还有其他几个类似的问题——但是有更多空的实现方法。
解决方案
嗯。像这个?
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();
}
}
推荐阅读
- python-3.x - ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()。在进行 KFold 交叉验证时
- mysql - 使用 laravel 和 vue js 从 mysql 数据库中检查带有逗号分隔值的复选框
- python - 在 pandas DataFrame 中选择特定值
- python - Pandas 基于事件的数据(数据科学)
- machine-learning - 如何在 python 上播放音频而不保存音频文件
- haskell - 如何使用 Haskell 中的数据构造函数?
- c++ - 引用成员绑定到一个临时对象,其生命周期将短于构造对象的生命周期
- python - 我在使用 pygmo 软件时遇到问题
- svg - 在 d3.js 中获取多条路径的质心
- c++ - /mingw32/bin/ld.exe:无法打开输出文件 HelloWorld.exe:权限被拒绝 collect2.exe:错误:ld 返回 1 退出状态