java 事件监听 - 鼠标
//事件监听
//鼠标事件监听
//鼠标事件监听有两个实现接口
//1、MouseListener 普通的鼠标操作
//2、MouseMotionListener 鼠标的拖拽、移动
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Index extends JFrame{
//设置面板
Wdmb wdmb = new Wdmb();
public static void main(String[] args) throws Exception{
//实例化当前类
Index index = new Index();
}
//自动执行
public Index(){
this.add(wdmb);
//添加鼠标监听事件
this.addMouseListener(wdmb);
//添加鼠标拖拽事件
this.addMouseMotionListener(wdmb);
this.setSize(500,500);
this.setLocation(300,200);
this.setTitle("绘图");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
//面板方法
//MouseListener 鼠标监听
//MouseMotionListener 鼠标拖拽监听
class Wdmb extends JPanel implements MouseListener,MouseMotionListener{
//方法覆盖
//JPanel自带方法,下面格式是固定的
//paint 会在三种情况下自动被调用
//1、启动程序 2、窗口大小发生变化时 3、运行repaint函数时
public void paint(Graphics g){
//覆盖父类的方法
super.paint(g);
}
/**
* 鼠标事件
*/
//鼠标单击
public void mouseClicked(MouseEvent e){
System.out.println("鼠标点击的位置是:");
System.out.println("X坐标:"+e.getX());
System.out.println("X坐标:"+e.getY());
}
//鼠标按下
public void mousePressed(MouseEvent e){
//System.out.println("鼠标被按下");
}
//鼠标松开
public void mouseReleased(MouseEvent e){
//System.out.println("鼠标被松开");
}
//鼠标移动到界面中
public void mouseEntered(MouseEvent e){
//System.out.println("鼠标移动到界面中");
}
//鼠标从界面离开
public void mouseExited(MouseEvent e){
//System.out.println("鼠标从界面离开");
}
/**
* 鼠标拖拽事件
*
*/
//鼠标拖拽
public void mouseDragged(MouseEvent e){
System.out.println("鼠标点击的位置是:");
System.out.println("X坐标:"+e.getX());
System.out.println("X坐标:"+e.getY());
}
//鼠标移动
public void mouseMoved(MouseEvent e){
System.out.println("鼠标点击的位置是:");
System.out.println("X坐标:"+e.getX());
System.out.println("X坐标:"+e.getY());
}
}