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


Updated on: 10-Feb-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements