[英]Prevent Button from firing when enter or space is pressed Javafx
I have a button on a Scene, that whenever the space bar or enter key is pressed, this button automatically fires.我在场景上有一个按钮,只要按下空格键或回车键,这个按钮就会自动触发。 I want the user to be able to type these keys without this button firing.我希望用户能够在不触发此按钮的情况下键入这些键。 I have already tried doing root.requestFocus()
and calling the request focus method on other nodes in my scene.我已经尝试过执行root.requestFocus()
并在我的场景中的其他节点上调用请求焦点方法。 How can I prevent this button from firing when these keys are pressed.当按下这些键时,如何防止此按钮触发。 Thanks for any help.谢谢你的帮助。
Edit: So far I have just done the boiler plate code to make a Javafx application work, added that button and a few labels.编辑:到目前为止,我刚刚完成了使 Javafx 应用程序工作的样板代码,添加了该按钮和一些标签。 I have tried the requestFocus() method in several nodes in my application, none of which has made a difference.我在我的应用程序的几个节点中尝试了 requestFocus() 方法,但没有一个有什么不同。 I also have a scene.setOnKeyPressed
action event listener for keys pressed.我还有一个用于按下按键的scene.setOnKeyPressed
动作事件侦听器。
You can use the button.setFocusTraversable()
method ( docs ).您可以使用button.setFocusTraversable()
方法 ( docs )。 This prevents the button from being focused automatically, eg by pressing TAB .这可以防止按钮自动聚焦,例如通过按TAB 。
Button button = new Button("Some Action");
button.setFocusTraversable(false);
button.setOnAction(event -> System.out.println("Some action called!"));
您是否尝试过为消耗事件的javafx.scene.input.KeyEvent
添加事件过滤器?
Say your defaultFocusNode
has focus, and you don't want your button
to do its default behavior of taking focus for itself (and away from defaultFocusNode
) when button
is clicked.假设你的defaultFocusNode
具有焦点,而你不希望你的button
做的考虑重点,本身它的默认行为(和远离defaultFocusNode
),当button
被点击。 When button
gets focus, this code will immediately give focus back to defaultFocusNode
.当button
获得焦点时,此代码将立即将焦点返回给defaultFocusNode
。
button.focusedProperty().addListener((observableValue, oldValue, newValue) -> {
if (newValue) defaultFocusNode.requestFocus();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.