本文介绍了在 JavaFX 中使用 Enter 触发按钮的 onAction的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 JavaFx 的新手.在我的 JavaFX 应用程序中,我设置了 onAction 属性,当我使用鼠标按下按钮时它工作正常.即使用户按 Enter 按钮,我也想触发相同的操作.我知道我可以使用偶数处理程序来做到这一点.但是当我阅读 onAction JavaDoc 时,它说这个事件会通过按键触发.

I'm a newbie to JavaFx. In my JavaFX application I have set onAction property and it works fine when I press the button using mouse. I want to fire the same even when user press Enter on button. I know I can use a even handler to do that.But when I read the onAction JavaDoc it says that this event get fire by a key press.

属性描述:

按钮的动作,每当按钮被触发.这可能是由于用户点击了使用鼠标按钮,或通过触摸事件,或按键,或者如果开发人员以编程方式调用 fire() 方法.

The button's action, which is invoked whenever the button is fired. This may be due to the user clicking on the button with the mouse, or by a touch event, or by a key press, or if the developer programmatically invokes the fire() method.

但是当我按下 Enter 键时,什么也没有发生.它是文档中的错误吗?有没有其他方法可以在不向按钮添加监听器的情况下实现这一目标?

But when I press Enter key nothing happens. Is it error in documentation? Are there any other way to achieve that without adding alistener to the button?

附言

在评论之后我用空格键检查然后它被解雇了.但我想将其设置为 Enter 键.我有很多按钮.我试过 button.setDefaultButton(true); 但它没有被解雇.我认为这是因为有不止一个按钮.如果我仅将其设置为单个按钮,则它可以正常工作.如何将其设置为多个按钮?

After the comments I checked with space key then it get fired. But I want to set that to Enter key.I have many buttons. I tried button.setDefaultButton(true); but it is not get fired. I think that is becacuse there are more than one button. If I set it just to a single button it works fine. How to set that to multiple buttons?

推荐答案

可以通过绑定动态改变当前焦点按钮的默认按钮属性

You can dynamically change the default button property of the currently focused button by using binding

btn.defaultButtonProperty().bind(btn.focusedProperty());

这篇关于在 JavaFX 中使用 Enter 触发按钮的 onAction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 17:37