Is there a way to take away focus in javafx?

27,495

Solution 1

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();
    }
}

Solution 2

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);
Share:
27,495
sazzy4o
Author by

sazzy4o

Updated on July 09, 2022

Comments

  • sazzy4o
    sazzy4o almost 2 years

    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?

  • Philip Vaughn
    Philip Vaughn almost 8 years
    Well not sure what you mean by node.setFocusTraversible(true) because setting it true will allow a node to have focus.
  • Doberon
    Doberon almost 8 years
    I search how able the focus, you solution help me to find the solution to my problem, thanks
  • Asif Mushtaq
    Asif Mushtaq almost 8 years
    @PhilipVaughn how to request focus textfield in FXML?
  • Philip Vaughn
    Philip Vaughn over 6 years
    @UnKnown Sorry it's been like 8 months since you commented but if you still have a question about TextField focus you should ask a brand new question because that's actually something that could take a bit of code depending on WHEN you need the control to have focus.