JavaFX:以编程方式聚焦文本框 [英] JavaFX: Focusing textfield programmatically

查看:1222
本文介绍了JavaFX:以编程方式聚焦文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用JavaFX编写了一个应用程序,它只能用于键盘的箭头。
所以我阻止在场景的舞台上的MouseEvent,并且我听到KeyEvents。
我还关闭所有节点的聚焦性:

  for(Node n:children){
n .setFocusTraversable(假);

现在我有一些文本框,复选框和按钮。
我想以编程方式更改我的输入控件(textfield,checkbox,..)的状态:例如我想输入文本框以编程内容。
所以我的问题是:如何进入非焦点遍历的文本框?
因为textfield.requestFocus();不再工作,因为我设置了false到ffieldstrableable属性我的文本框。



谢谢

解决方案

  n.setFocusTraversable(false); 

节点是非焦点遍历的,而不是不可聚焦的。它仍然可以通过鼠标或程序化来集中。因为你阻止了鼠​​标事件,这里是另一个选项:

  Platform.runLater(new Runnable(){
@Override
public void run(){
textfield.requestFocus();
}
});

场景场景=新场景(根);

编辑:根据评论


...有资格获得焦点,节点必须是场景的一部分,
它的所有祖先必须是可见的,并且它不能被禁用
。 ...


所以这个方法应该在构建场景图之后调用如下:

 场景场景=新场景(根); 
textfield.requestFocus();

然而,上面的Platform.runLater将在最后运行,主要方法之后 start(),确保requestFocus的调用将在场景图形协调之后。



还有其他原因取决于requestFocus实施代码。


I wrote an application with JavaFX which will only be usable with keyboard's arrows. So I prevented MouseEvent on Scene's stage, and I "listen" to KeyEvents. I also switched off focusability of all nodes :

for(Node n : children) {
     n.setFocusTraversable(false);

Now I have some textfields, checkboxes, and buttons. I would like to change the state of my input controls (textfield, checkbox,..) programatically: for example I would like to enter the textfield to edit the content programatically. So my question is: how to enter in a non-focus-traversable textfield? Because textfield.requestFocus(); doesn't work anymore since I set false to focustraversable property of my textfield.

Thanks

解决方案

By

n.setFocusTraversable(false);

the node is made non-focus-traversable instead of non-focusable. It can still be focused for example by mouse or programmatically. Since you prevented mouse events, here the other option:

Platform.runLater(new Runnable() {
    @Override
    public void run() {
        textfield.requestFocus();
    }
});

Scene scene = new Scene(root);

EDIT: as per comment,
The javadoc of requestFocus states:

... To be eligible to receive the focus, the node must be part of a scene, it and all of its ancestors must be visible, and it must not be disabled. ...

So this method should be called after construction of scene graph as follow:

Scene scene = new Scene(root);
textfield.requestFocus();

However, Platform.runLater in the above will run at the end, after the main method start(), which ensures the call of requestFocus will be after scene graph cosntruction.

There maybe other reasons depending on the requestFocus implementation code.

这篇关于JavaFX:以编程方式聚焦文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆