Java JButton handle mouse event
import java.awt.Component; import java.awt.GridLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JButton; import javax.swing.JFrame; class MouseEnterFocusMover extends MouseAdapter { public void mouseEntered(MouseEvent mouseEvent) { Component component = mouseEvent.getComponent(); if (!component.hasFocus()) { component.requestFocusInWindow(); }/* w w w. j ava 2 s . c om*/ } } public class Main { public static void main(String args[]) { JFrame frame = new JFrame("Focus Sample"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); MouseListener mouseListener = new MouseEnterFocusMover(); frame.setLayout(new GridLayout(3, 3)); JButton button = new JButton("0"); button.addMouseListener(mouseListener); button.setFocusable(false); frame.add(button); button = new JButton("1"); button.addMouseListener(mouseListener); frame.add(button); button = new JButton("2"); button.addMouseListener(mouseListener); frame.add(button); frame.setSize(300, 200); frame.setVisible(true); } }
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("Mouse"); public Main() { super("Handling Mouse Event"); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setLayout(new FlowLayout()); this.getContentPane().add(mouseButton); // Add a MouseListener to the JButton mouseButton.addMouseListener(new MouseListener() { @Override/*from w w w . j a v a 2 s . com*/ 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); } }