为什么在使用 MouseAdapter 时未收到 mouseDragged 事件?
2022-09-03 04:46:23
为什么 -events 仅在使用时接收,而不在使用
时接收 ?mouseDragged
MouseMotionAdapter
MouseAdapter
Java有两个抽象的适配器类,用于接收鼠标事件;
和。MouseAdapter
MouseMotionAdapter
两个类都有一个 -方法,但 中的
一个似乎不起作用 ;-事件
永远不会通过这个。mouseDragged(MouseEvent e)
MouseAdapter
mouseDragged
这两个类都实现了
定义 -event 的 -interface,所以我不明白为什么它
不能在它们两个类上正常工作。MouseMotionListener
mouseDragged
下面是显示此问题的示例代码:
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
public class SwingApp extends JFrame
{
public SwingApp()
{
// No mouseDragged-event is received when using this :
this.addMouseListener(new mouseEventHandler());
// This works correct (when uncommented, of course) :
// this.addMouseMotionListener(new mouseMovedEventHandler());
setBounds(400,200, 550,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
public static void main(String args[])
{
new SwingApp();
}
class mouseEventHandler extends MouseAdapter
{
@Override
public void mouseDragged(MouseEvent e) // Why is this method never called ?
{
System.out.println(String.format("MouseDragged via MouseAdapter / X,Y : %s,%s ", e.getX(), e.getY()));
}
}
class mouseMovedEventHandler extends MouseMotionAdapter
{
@Override
public void mouseDragged(MouseEvent e)
{
System.out.println(String.format("MouseDragged via MouseMotionAdapter / X,Y : %s,%s ", e.getX(), e.getY()));
}
}
}