java之事件监听(三)鼠标监听

  • Post author:
  • Post category:java


package 第一版;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.*;
public class draw5 extends JFrame{
	My_Panel mp = null;
	public draw5() {
		// TODO Auto-generated constructor stub
		mp = new My_Panel();
		this.add(mp);
		// 注册监听
		this.addMouseListener(mp); // 监听鼠标
		this.addKeyListener(mp); // 监听键盘
		this.addMouseMotionListener(mp); // 监听鼠标移动
		
		this.setSize(300, 300); // 设置框体大小
		this.setLocation(400,150); //设置框体显示的位置
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置框体退出
		this.setVisible(true); // 显示框体
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		draw5 d = new draw5();
	}

}

class My_Panel extends JPanel implements MouseListener,KeyListener,MouseMotionListener{
	public void paint(Graphics g){
		super.paint(g);
	}
	//鼠标点击
	@Override
	public void mouseClicked(MouseEvent e) {
		// TODO Auto-generated method stub
		System.out.println("鼠标点击");
		System.out.println("鼠标位置 x = "+e.getX()+" y = "+e.getY());
		System.out.println("鼠标键 = "+e.getButton() + " 点击次数 "+e.getClickCount()); // 输出1是左键,2是中键,3是右键
	}
	//鼠标移动到My_Panel
	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
	//	System.out.println("鼠标移动到My_Panel");
	}
	//鼠标离开My_Panel
	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
	//	System.out.println("鼠标离开My_Panel");
	}
	//鼠标按下
	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
	//	System.out.println("鼠标按下");
	}
	//鼠标松开
	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
	//	System.out.println("鼠标松开");
	}
	//键按下
	@Override
	public void keyPressed(KeyEvent e) {
		// TODO Auto-generated method stub
		System.out.println("键  = "+e.getKeyChar());
		
	}
	//键松开
	@Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}
	//键输入
	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}
	//鼠标按键在组件上按下并拖动时调用
	@Override
	public void mouseDragged(MouseEvent e) {
		// TODO Auto-generated method stub
	//	System.out.println("鼠标按键在组件上按下并拖动时调用");
	}
	//鼠标光标移动到组件上但无按键按下时调用
	@Override
	public void mouseMoved(MouseEvent e) {
		// TODO Auto-generated method stub
	//	System.out.println("鼠标光标移动到组件上但无按键按下时调用");
	}
}



版权声明:本文为lijunqiangacm原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。