- 确保您与 UI 的所有交互都是在事件调度线程的上下文中执行的
- 使用
requestFocusInWindow
代替requestFocus
,requestFocus
取决于系统,因此其功能未定义
Robot
您可以通过使用该类将鼠标光标的位置更改为坐在按钮上。
您将需要使用Component#getLocationOnScreen
和的组合Robot#mouseMove
就像是...
try {
button.requestFocusInWindow();
Robot bot = new Robot();
Point pos = button.getLocationOnScreen();
bot.mouseMove(pos.x + (button.getWidth() / 2), pos.y + (button.getHeight() / 2));
} catch (AWTException ex) {
Logger.getLogger(TestRobot.class.getName()).log(Level.SEVERE, null, ex);
}
更新示例
好的,这是一个工作示例。这有一个内置的计时器,可以简单地移动到下一个可聚焦的组件。
我在每个按钮上附加了一个焦点组件,将鼠标移动到每个按钮的中心。
这意味着您可以让计时器移动到下一个组件或按 Tab,您应该得到相同的结果
public class TestFocusTransversal {
public static void main(String[] args) {
new TestFocusTransversal();
}
public TestFocusTransversal() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ButtonPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
});
}
public class ButtonPane extends JPanel {
public ButtonPane() {
setLayout(new GridLayout(3, 2));
FocusHandler focusHandler = new FocusHandler();
ActionHandler actionHandler = new ActionHandler();
for (int index = 0; index < 6; index++) {
JButton button = new JButton("Button " + index);
button.addActionListener(actionHandler);
button.addFocusListener(focusHandler);
add(button);
}
}
}
public class FocusHandler extends FocusAdapter {
@Override
public void focusGained(FocusEvent e) {
try {
Robot bot = new Robot();
Component component = e.getComponent();
Point pos = component.getLocationOnScreen();
bot.mouseMove(pos.x + (component.getWidth() / 2), pos.y + (component.getHeight() / 2));
} catch (AWTException ex) {
ex.printStackTrace();
}
}
}
public class ActionHandler implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton button = ((JButton)e.getSource());
System.out.println("Fired " + button.getText());
}
}
}