import java.awt.Component;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
public class FocusSample {
public static void main(String args[]) {
JFrame frame = new JFrame("Focus Sample");
ActionListener actionListener = new ActionFocusMover();
MouseListener mouseListener = new MouseEnterFocusMover();
Container contentPane = frame.getContentPane();
contentPane.setLayout(new GridLayout(3, 3));
for (int i = 1; i < 10; i++) {
JButton button = new JButton("" + i);
button.addActionListener(actionListener);
button.addMouseListener(mouseListener);
if ((i % 2) != 0) {
button.setRequestFocusEnabled(false);
}
contentPane.add(button);
}
frame.setSize(300, 200);
frame.setVisible(true);
}
}
class ActionFocusMover implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
Object source = actionEvent.getSource();
if (source instanceof Component) {
Component component = (Component) source;
component.transferFocus();
}
}
}
class MouseEnterFocusMover extends MouseAdapter {
public void mouseEntered(MouseEvent mouseEvent) {
Component component = mouseEvent.getComponent();
if (!component.hasFocus()) {
component.requestFocus();
}
}
}
|