📅  最后修改于: 2020-09-29 01:24:09             🧑  作者: Mango
每当您移动或拖动鼠标时,都会通知Java MouseMotionListener。会根据MouseEvent进行通知。 MouseMotionListener接口位于java.awt.event包中。它有两种方法。
下面给出在MouseMotionListener接口中找到的2种方法的签名:
public abstract void mouseDragged(MouseEvent e);
public abstract void mouseMoved(MouseEvent e);
import java.awt.*;
import java.awt.event.*;
public class MouseMotionListenerExample extends Frame implements MouseMotionListener{
MouseMotionListenerExample(){
addMouseMotionListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {}
public static void main(String[] args) {
new MouseMotionListenerExample();
}
}
输出:
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class Paint extends Frame implements MouseMotionListener{
Label l;
Color c=Color.BLUE;
Paint(){
l=new Label();
l.setBounds(20,40,100,20);
add(l);
addMouseMotionListener(this);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e) {
l.setText("X="+e.getX()+", Y="+e.getY());
Graphics g=getGraphics();
g.setColor(Color.RED);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {
l.setText("X="+e.getX()+", Y="+e.getY());
}
public static void main(String[] args) {
new Paint();
}
}
输出: