[英]Giving a button mouse click focus
希望我能很好地解释这一点,使之有意义。
我的堂兄已被禁用,并使用一个按钮来控制计算机上的应用程序。 所有这些应用程序都是定制的,它们依赖于循环焦点和加粗显示的按钮。 这样,您只需在按钮突出显示时单击即可,从而无需移动鼠标。
我目前正在为他做一个小游戏,我在专注部分上遇到了麻烦。 我正在使用一个线程来循环焦点和LayoutButton.requestFocus();
得到焦点。
如果按下空格键,这将起作用,但是他使用的按钮却按下了鼠标左键。
有没有一种方法可以将按钮的焦点设置为鼠标左键? 因此,鼠标将必须有效地指向按钮,因此当您单击鼠标时,按钮将被按下。 然后,它将不得不使该按钮失去焦点,然后将焦点重新放在下一个按钮上。 说得通?
如果有人能指出我正确的方向,我将不胜感激。 谢谢!
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());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.