TextField中的RequestFocus不起作用 [英] RequestFocus in TextField doesn't work

查看:107
本文介绍了TextField中的RequestFocus不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用JavaFX 2.1并使用FXML创建了GUI,在此GUI的控制器中我添加了 myTextField.requestFocus();

I use JavaFX 2.1 and I created GUI using FXML, in the controller of this GUI I added myTextField.requestFocus();.

但我总是把焦点放在另一个控件上。

But I always get the focus in the other control.

推荐答案

在<$ c时$ c> initialize()控件尚未准备好处理焦点。

At the time of initialize() controls are not yet ready to handle focus.

您可以尝试下一招:

@Override
public void initialize(URL url, ResourceBundle rb) {
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            tf.requestFocus();
        }
    });
}

对于棘手的复杂应用程序(如评论中的Pavel_K),您可能希望多次重复此例程并调用方法行下一个:

For tricky complex applications (like Pavel_K has in the comments) you may want to repeat this routine several times and call method line next one:

private void repeatFocus(Node node) {
    Platform.runLater(() -> {
        if (!node.isFocused()) {
            node.requestFocus();
            repeatFocus(node);
        }
    });
}

注意这是未记录的方法,添加重复限制可能是明智之举如果在未来的Java版本中发生了变化或破坏,请避免无限循环。最好是失去焦点而不是整个应用程序。 :)

Note this is undocumented approach and it may be wise to add a limit for repetitions to avoid endless loop if something changed or broke in future Java releases. Better to lose focus than a whole app. :)

这篇关于TextField中的RequestFocus不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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