如何检测当鼠标在 Java 中移动到任何组件时的事件?
当鼠标稳定在处理鼠标事件时,我们可以实现一个MouseListener接口。当我们可以在源对象上按下、释放或单击(按下然后释放)鼠标按钮(左键或右键),或将鼠标指针定位于(进入)源对象和从源对象移开(离开)时,MouseEvent就会触发。通过使用MouseAdapter类的mouseEntered()方法,可以检测当鼠标移动到任何组件(例如标签)上的鼠标事件,而可以通过使用MouseAdapter类或MouseListener接口的mouseExited()方法退出。
示例
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseOverTest extends JFrame {
private JLabel label;
public MouseOverTest() {
setTitle("MouseOver Test");
setLayout(new FlowLayout());
label = new JLabel("Move the mouse moves over this JLabel");
label.setOpaque(true);
add(label);
label.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent evt) {
Color c = label.getBackground(); // When the mouse moves over a label, the background color changed.
label.setBackground(label.getForeground());
label.setForeground(c);
}
public void mouseExited(MouseEvent evt) {
Color c = label.getBackground();
label.setBackground(label.getForeground());
label.setForeground(c);
}
});
setSize(400, 275);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new MouseOverTest();
}
}输出
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP