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

Java MouseListener接口

本文概述

每当你更改鼠标状态时, 都会通知Java MouseListener。根据MouseEvent进行通知。可在java.awt.event包中找到MouseListener接口。它有五种方法。

MouseListener接口的方法

在MouseListener界面中找到的5种方法的签名如下:

public abstract void mouseClicked(MouseEvent e);
public abstract void mouseEntered(MouseEvent e);
public abstract void mouseExited(MouseEvent e);
public abstract void mousePressed(MouseEvent e);
public abstract void mouseReleased(MouseEvent e);

Java MouseListener示例

import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
	Label l;
	MouseListenerExample(){
		addMouseListener(this);
		
		l=new Label();
		l.setBounds(20, 50, 100, 20);
		add(l);
		setSize(300, 300);
		setLayout(null);
		setVisible(true);
	}
	public void mouseClicked(MouseEvent e) {
		l.setText("Mouse Clicked");
	}
	public void mouseEntered(MouseEvent e) {
		l.setText("Mouse Entered");
	}
	public void mouseExited(MouseEvent e) {
		l.setText("Mouse Exited");
	}
	public void mousePressed(MouseEvent e) {
		l.setText("Mouse Pressed");
	}
	public void mouseReleased(MouseEvent e) {
		l.setText("Mouse Released");
	}
public static void main(String[] args) {
	new MouseListenerExample();
}
}

输出:

java awt mouselistener示例1

Java MouseListener示例2

import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample2 extends Frame implements MouseListener{
	MouseListenerExample2(){
		addMouseListener(this);
		
		setSize(300, 300);
		setLayout(null);
		setVisible(true);
	}
	public void mouseClicked(MouseEvent e) {
		Graphics g=getGraphics();
		g.setColor(Color.BLUE);
		g.fillOval(e.getX(), e.getY(), 30, 30);
	}
	public void mouseEntered(MouseEvent e) {}
	public void mouseExited(MouseEvent e) {}
	public void mousePressed(MouseEvent e) {}
	public void mouseReleased(MouseEvent e) {}
	
public static void main(String[] args) {
	new MouseListenerExample2();
}
}

输出:

java awt mouselistener示例2
赞(0)
未经允许不得转载:srcmini » Java MouseListener接口

评论 抢沙发

评论前必须登录!