Java MouseMotionListener接口

本文概述

  • MouseMotionListener接口的方法
  • Java MouseMotionListener示例
  • Java MouseMotionListener示例2
每当你移动或拖动鼠标时, 都会通知Java MouseMotionListener。根据MouseEvent进行通知。可在java.awt.event包中找到MouseMotionListener接口。它有两种方法。
MouseMotionListener接口的方法 下面给出在MouseMotionListener接口中找到的2种方法的签名:
public abstract void mouseDragged(MouseEvent e); public abstract void mouseMoved(MouseEvent e);

Java MouseMotionListener示例
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(); } }

输出:
Java MouseMotionListener接口

文章图片
Java MouseMotionListener示例2
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(); } }

【Java MouseMotionListener接口】输出:
Java MouseMotionListener接口

文章图片

    推荐阅读