Is there a way to take away focus in javafx?

左心房为你撑大大i 提交于 2019-12-01 05:19:11

I don't think there's any guarantee this will always work, but you can try setting focus to something that inherently doesn't accept keyboard input (such as a layout pane):

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class NoFocusTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        TextField tf1 = new TextField();
        tf1.setPromptText("Enter something");
        TextField tf2 = new TextField();
        tf2.setPromptText("Enter something else");
        VBox root = new VBox(5, tf1, tf2);
        primaryStage.setScene(new Scene(root, 250, 150));
        primaryStage.show();
        root.requestFocus();
    }
}
Philip Vaughn
node = new node() {
  public void requestFocus() { }
};

Now this will override the focus and the node will NEVER be able to have focus. You could also (as stated before) disable the node with:

node.setDisable(true);

If you need focus later:

node.setDisable(false);
node.requestFocus();

I decided to update my answer to this with one more option. If you are giving another node focus at the start of the program you could set a particular node to be non-traversable and it will not gain focus.

node.setFocusTraversable(false);

If you have another node then you can remove focus from your node and give it to another with this.

otherNode.requestFocus();

By doing this you won't need to disable or enable your original node.

Some nodes such as a Label won't look different when they have focus, so this can make it appear as if focus was removed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!