本文共 1790 字,大约阅读时间需要 5 分钟。
随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)、QQ技术交流群(183198395)。
MouseMotionListener 用于接收组件上的鼠标移动事件的侦听器接口。旨在处理鼠标移动事件的类要么实现此接口(及其包含的所有方法),要么扩展抽象类 MouseMotionAdapter(仅重写有用的方法)。
然后使用组件的addMouseMotionListener 方法将从该类所创建的侦听器对象向该组件注册。移动或拖动鼠标时会生成鼠标移动事件。(将生成很多此类事件)。发生鼠标移动事件时,将调用该侦听器对象中的相应方法,并将MouseEvent
传递给该方法。
此接口包括两个方法:
1.public void mouseDragged(MouseEvent e)
鼠标按键在组件上按下并拖动时调用。(处理鼠标拖动事件)
2.public void mouseMoved(MouseEvent e)
鼠标光标移动到组件上但无按键按下时调用。(处理鼠标移动事件)
下面看一个直接实现MouseMotionListener接口的例子:鼠标移动或拖动时,给出提示并显示鼠标所在位置的坐标。
package cn;import java.awt.*;import java.awt.event.*;import javax.swing.JFrame;import javax.swing.JButton;public class MyMouseMotionListener implements MouseMotionListener { JFrame myframe; // JFrame通常默认使用BorderLayout布局管理器的 TextArea tf; JButton exitButton; int number = 1; public MyMouseMotionListener() { Label label = new Label("click and drag the mouse"); myframe = new JFrame("MyMouseMotionListener"); tf = new TextArea(); exitButton = new JButton("退出"); tf.addMouseMotionListener(this); exitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); myframe.add(label, BorderLayout.NORTH); myframe.add(tf, BorderLayout.CENTER); myframe.add(exitButton, BorderLayout.SOUTH); myframe.setSize(400, 300); myframe.setVisible(true); } public static void main(String[] args) { new MyMouseMotionListener(); } @Override // 负责处理鼠标拖动事件 public void mouseDragged(MouseEvent e) { //getX(),getY():获取鼠标的坐标位置 String s = number++ + "" + "the mouse is draggered:x=" + e.getX() + "y=" + e.getY() + "\n"; tf.append(s); } @Override // 负责处理鼠标移动事件 public void mouseMoved(MouseEvent e) { String s = number++ + "" + "the mouse is moving:x=" + e.getX() + "y=" + e.getY() + "\n"; tf.append(s); }}
转载地址:http://vvtei.baihongyu.com/