- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we detect an event when the mouse moves over any component in Java?
We can implement a MouseListener interface when the mouse is stable while handling the mouse event. A MouseEvent is fired when we can press, release or click (press followed by release) a mouse button (left or right button) at the source object or position the mouse pointer at (enter) and away (exit) from the source object. We can detect a mouse event when the mouse moves over any component such as a label by using the mouseEntered() method and can be exited by using mouseExited() method of MouseAdapter class or MouseListener interface.
Example
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(); } }
Output
Advertisements