Is there a way to take away focus in javafx?


I know that your can give focus to a node in javafx by doing node.requestFocus(); but is there a way to take away focus from a node in javafx or prevent focus on an object?

8/21/2014 5:03:31 PM

Accepted Answer

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 {

    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));;
8/21/2014 6:10:05 PM

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:


If you need focus later:


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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow