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();
}
}
标签:Java,鼠标,MouseListener,void,MouseMotionListener,add,new,JLabel,public 来源: https://blog.csdn.net/weixin_54702911/article/details/122135769