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(); } } } public class FocusSampleMouseEnterFocusMover { 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)); for (int i = 1; i < 10; i++) { JButton button = new JButton(Integer.toString(i)); button.addMouseListener(mouseListener); if ((i % 2) != 0) { button.setFocusable(false); } frame.add(button); } frame.setSize(300, 200); frame.setVisible(true); } }