个性化阅读
专注于IT技术分析

Java MouseMotionListener接口

本文概述

每当你移动或拖动鼠标时, 都会通知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 awt mousemotionlistener示例1

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 awt mousemotionlistener示例2
赞(0)
未经允许不得转载:srcmini » Java MouseMotionListener接口

评论 抢沙发

评论前必须登录!