鼠标操作是图形操作系统最常用操作,用户使用鼠标单击,双击,右击,拖动等操作实现与软件的交互。 鼠标事件监听器 鼠标事件监听器由MouseListener接口和MouseMotionListener接口定义,分别定义鼠标捕获不同的鼠标操作方法。 MouseListener监听器方法说明 mouseClicked(MouseEvent e) 处理鼠标单击事件方法
mouseEntered(MouseEvent e) 鼠标进入组件区域时执行方法 mouseExited(MouseEvent e) 鼠标离开组件区域执行方法 mousePressed(MouseEvent e) 按下鼠标按键时执行方法 mouseRelease(MouseEvent e) 释放鼠标按键时执行方法
MouseListener监听器的方法,基本满足大多数程序需求。
MouseMotionListener接口定义两个有关鼠标移动和拖动事件的处理方法。 MouseMotionListener监听器方法说明
mouseMoved(MouseEvent e) 处理鼠标移动事件的方法 mouseDragged(MouseEvent e) 处理鼠标拖动事件的方法 鼠标事件处理 两个鼠标事件监听器中的方法都定义了MouseEvent类型的形参,MouseEvent类是鼠标事件类,是被监听器捕获的用户操作所生成的事件对象,该实例对象包含了许多鼠标事件发生时的参数信息。例如鼠标的坐标位置,鼠标的按键等。
常用方法有: getButton() 返回更改了状态的鼠标按键
getClickCount() 返回与此事件关联的鼠标单击次数
getLocationOnScreen() 返回鼠标相对于屏幕的绝对x,y坐标
getPoint() 返回事件相对于源组件的x,y坐标
translatePoint() 通过将事件坐标加上指定x,y偏移量,将事件坐标平移到新位置 以下代码,演示了两个接口的作用,通过读代码,就会理解到各自方法的作用:
importjavax.swing.*;
importjava.awt.event.*;
publicclassMyMouse extendsJFrame{
publicJLabeljl= newJLabel("鼠标暂无操作 ");
publicMyMouse(){
setBounds(100,100,350,80);
getContentPane().add("South",jl);
addMouseListener( newMouseListener(){
publicvoidmouseClicked(MouseEventarg0){
jl.setText("鼠标在界面中单击了 "+jl.getText()+arg0.getClickCount()
+"次 ");
}
publicvoidmouseEntered(MouseEventarg0){
jl.setText("鼠标进入了窗体界面 ");
}
publicvoidmouseExited(MouseEventarg0){
jl.setText("鼠标离开了窗体界面 ");
}
publicvoidmousePressed(MouseEventarg0){
jl.setText("鼠标在窗体界面中按下了键 "+arg0.getButton());
}
publicvoidmouseReleased(MouseEventarg0){
jl.setText("鼠标在窗体界面中释放了键 "+arg0.getButton());
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
publicstaticvoidmain(String[]args){
MyMousetest= newMyMouse();
test.setVisible( true);
}
}
以下代码,演示了MouseMotionListener类,组件在界面中,可以拖动:
importjavax.swing.*;
importjava.awt.FlowLayout;
importjava.awt.event.*;
publicclassMyMouse extendsJFrame{
publicJButtonjb= newJButton("鼠标可拖动按钮 ");
publicJTextFieldjt= newJTextField();
publicMyMouse(){
jb.setBounds(100,100,330,175);
jt.setColumns(20);
setBounds(100,100,350,280);
getContentPane().setLayout( newFlowLayout());
getContentPane().add(jb);
getContentPane().add(jt);
addMouseMotionListener( newMouseMotionListener(){
/**
*处理鼠标拖动事件
**/
publicvoidmouseDragged(MouseEventarg0){
mouseMoved(arg0);
jb.setLocation(arg0.getPoint());
}
/**
*处理鼠标移动事件
**/
publicvoidmouseMoved(MouseEventarg0){
jt.setText(arg0.getPoint().toString());
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
publicstaticvoidmain(String[]args){
MyMousetest= newMyMouse();
test.setVisible( true);
}
}