AWT事件监听作业学习例子(3) - MouseEvent + MouseWheelEvent
【事件执行情况】MouseEvent - 与鼠标事件相关联的操作时执行 ; MouseWheelEvent - 鼠标滚轮在组件中滚动时执行 【传递的接口名】MouseListener,MouseMotionListener + MouseWheelListener 【需要实现方法】MouseListener:mouseClicked - 鼠标按键在组件上单击(按下并释放)时调用; mouseEntered - 鼠标进入到组件上时调用;mouseExited - 鼠标离开组件时调用;mousePressed - 鼠标按键在组件上按下时调用;mouseReleased - 鼠标按钮在组件上释放时调用; MouseMotionListener:mouseDragged - 鼠标按键在组件上按下并拖动时调用;mouseMoved - 鼠标光标移动到组件上但无按键按下时调用 MouseWheelListener:mouseWheelMoved - 鼠标滚轮旋转时调用 【样例】鼠标在panel上动作/当前鼠标位置/滚轮状态 |
-
import javax.swing.*;
-
-
import java.awt.*;
-
import java.awt.event.*;
-
-
public class CallByMouse {
-
-
/**
-
* @author Linyq.
-
*/
-
MyFrame frm = new MyFrame();
-
}
-
-
}
-
-
-
public MyFrame(){
-
this.setTitle("MouseEvent 测试");
-
this.setSize(600,300);
-
-
this.getContentPane().add(label);
-
// 此文本标签用来记录鼠标动作
-
-
this.getContentPane().add(xy);
-
// 此文本标签用来显示当前鼠标坐标
-
-
this.getContentPane().add(wheel);
-
// 此文本标签用来显示滚轮状态
-
-
// panel
-
panel.setLayout(null);
-
panel.setSize(500,200);
-
this.getContentPane().add(panel);
-
-
// 鼠标事件(按下、释放、单击、进入或离开)的侦听器接口
-
-
// 鼠标按键在组件上单击(按下并释放)时调用
-
label.setText("鼠标在panel容器上单击(按下并释放)");
-
}
-
-
// 鼠标进入到组件上时调用
-
label.setText("鼠标进入panel容器");
-
}
-
-
// 鼠标离开组件时调用
-
label.setText("鼠标离开panel容器");
-
}
-
-
// 鼠标按键在组件上按下时调用
-
if(e.getClickCount()==2){
-
}
-
if(e.getButton()==e.BUTTON3){
-
label.setText("鼠标右键在panel容器上按下");
-
}
-
if(e.getButton()==e.BUTTON1){
-
label.setText("鼠标左键在panel容器上按下");
-
}
-
if(e.getButton()==e.BUTTON2){
-
label.setText("鼠标中键在panel容器上按下");
-
}
-
}
-
-
// 鼠标按钮在组件上释放时调用
-
label.setText("鼠标在panel容器上释放");
-
}
-
-
});
-
// 鼠标移动事件的侦听器接口
-
-
@Override
-
// 鼠标按键在组件上按下并拖动时调用
-
label.setText("鼠标在panel上按下并拖动");
-
}
-
-
@Override
-
// 鼠标光标移动到组件上但无按键按下时调用
-
xy.setText("当前位置 (x:" + e.getX() + ",y:" + e.getY() + ") ");
-
}
-
-
});
-
-
// 鼠标滚轮事件的侦听器接口
-
panel.addMouseWheelListener(new MouseWheelListener(){
-
-
@Override
-
public void mouseWheelMoved(MouseWheelEvent e) {
-
// 鼠标滚轮旋转时调用
-
wheel.setText("滚轮向" + (e.getWheelRotation()>0?"下":"上") + "滚动");
-
}
-
-
});
-
-
this.setVisible(true);
-
}
-
-
}