MouseListener和MouseMotionListener鼠标事件(Java)
2021/12/24 22:09:20
本文主要是介绍MouseListener和MouseMotionListener鼠标事件(Java),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
使用鼠标触发相应事件:
代码实现:
import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; //鼠标事件 public class MouseListenerTest extends JFrame implements MouseListener, MouseMotionListener { JPanel p1 = new JPanel(); JPanel p2 = new JPanel(); JPanel p3 = new JPanel(); JLabel lb1 = new JLabel(); JLabel lb2 = new JLabel(); JLabel lb3 = new JLabel(); JLabel lb4 = new JLabel(); JLabel lb5 = new JLabel(); JLabel lb6 = new JLabel(); JLabel lb7 = new JLabel(); Box box = Box.createVerticalBox(); public void init(){ this.setTitle("鼠标实例"); this.add(p1); this.add(p2); this.add(p3); p1.setLayout(new FlowLayout());//添加流水布局管理器 p2.setLayout(new FlowLayout()); p3.setLayout(new FlowLayout()); p1.setBounds(0,0,150,200);//设置面板大小和位置 p2.setBounds(150,0,150,200); p2.setBackground(Color.blue); //设置中间面板的背景颜色 p3.setBounds(300,0,150,200); p1.add(lb1); //将JLabel组件添加到面板中 p1.add(lb2); p1.add(lb3); p2.add(lb6); p2.add(lb7); p3.add(lb4); p3.add(lb5); p1.addMouseListener(this);//鼠标点击事件 p2.addMouseMotionListener(this);//鼠标移动事件 p3.addMouseListener(this);//鼠标点击事件 this.setLayout(null); this.setBounds(700,300,450,200); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } @Override public void mouseClicked(MouseEvent e) { //鼠标单击事件,在鼠标单击时触发 lb5.setText("鼠标单击了一次!"); } @Override public void mousePressed(MouseEvent e) { //鼠标按下事件,在鼠标按下时触发 int x = e.getX(); int y = e.getY(); lb2.setText("鼠标被按下 X轴 = "+x+"Y轴 = "+y); } @Override public void mouseReleased(MouseEvent e) { //鼠标释放事件,在鼠标释放时触发 lb1.setText("鼠标被释放了!"); } @Override public void mouseEntered(MouseEvent e) { //鼠标进入事件,在鼠标进入某控件时触发 lb4.setText("鼠标进入当前控件了!"); } @Override public void mouseExited(MouseEvent e) { //鼠标退出事件,在鼠标退出某控件时触发 lb3.setText("鼠标退出当前控件了!"); } @Override public void mouseDragged(MouseEvent e) { //鼠标拖拽事件,在鼠标拖动的时候触发 lb7.setText("鼠标拖动了!"); } @Override public void mouseMoved(MouseEvent e) { //鼠标移动事件,在鼠标移动时触发 lb6.setText("鼠标移动了!"); } public static void main(String[] args) { new MouseListenerTest().init(); } }
这篇关于MouseListener和MouseMotionListener鼠标事件(Java)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)
- 2024-05-30【Java】百万数据excel导出功能如何实现
- 2024-05-30我们小公司,哪像华为一样,用得上IPD(集成产品开发)?
- 2024-05-30java excel上传--poi
- 2024-05-30安装笔记本应用商店的pycharm,再安排pandas等模块,说是没有打包工具?
- 2024-05-29java11新特性