Reece Walsh
Reece Walsh

Reputation: 3

JAVAFX - How to make a textfield active on event action

GridPane layout = new GridPane();

    Label wordInstruction = new Label("Word");
    TextField wordField = new TextField();
    Label translationInstruction = new Label("Translation");
    TextField translationField = new TextField();
    Label error = new Label();

    layout.setVgap(10);
    layout.setHgap(10);
    layout.setPadding(new Insets(10, 10, 10, 10));
    layout.setAlignment(Pos.CENTER);

    Button addButton = new Button("Add");
    // Stops the button from consuming mouse events and allows it to become the default button.
    addButton.setSkin(new ButtonSkin(addButton) {
        {
            this.consumeMouseEvents(false);
        }
    });
    // The button can now be pressed with the enter key.
    addButton.setDefaultButton(true);

    layout.add(wordInstruction, 0, 0);
    layout.add(wordField, 0, 1);
    layout.add(translationInstruction, 0, 2);
    layout.add(translationField, 0, 3);
    layout.add(addButton, 0, 4);
    layout.add(error, 0, 6);

    addButton.setOnAction((event) -> {
        String word = wordField.getText();
        String translation = translationField.getText();

        if (!translationField.getText().isEmpty()) {
            this.dictionary.add(word.toLowerCase(), translation.toLowerCase());
            error.setText("");
            wordField.clear();
        } else {
            error.setText("Please input a translation.");
        }

        translationField.clear();
    });

    return layout;
}

Hello, I've just started using JavaFX and I've not been able to find anything in the documentation related to my problem. When I press the addButton, I want the user to be able to write into the wordField textField straight away instead of having to click it or tab all the way to it. Is there any way to make the textField active in my addButton.setOnAction function?

Thank you in advance.

Upvotes: 0

Views: 66

Answers (1)

queeg
queeg

Reputation: 9384

How about running the TextField.requestFocus() method?

Upvotes: 4

Related Questions