Java examples for Swing:Mouse Event
You can handle mouse event (clicked, entered, exited, pressed, and released) on a component.
The MouseEvent class has many methods that provide the details about a mouse event:
The following code has an implementation for all five methods of the MouseListener interface.
import java.awt.FlowLayout; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JButton; import javax.swing.JFrame; public class Main extends JFrame { JButton mouseButton = new JButton("No Mouse Movement Yet!"); public Main() { super("Handling Mouse Event"); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setLayout(new FlowLayout()); this.getContentPane().add(mouseButton); mouseButton.addMouseListener(new MouseListener() { @Override//w w w.j a v a 2 s.c om public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { mouseButton.setText("Mouse has entered!"); } @Override public void mouseExited(MouseEvent e) { mouseButton.setText("Mouse has exited!"); } }); } public static void main(String[] args) { Main frame = new Main(); frame.pack(); frame.setVisible(true); } }