Is there a way to select a text field in code without clicking on it (javafx)?


I am not sure how to or even if it is possible to select text fields in code. I could not find anything on the subject. If the is indeed a way to do so i have a template that could be modified to demonstrate how this could be done.

Here is the template/sample code:

Main class:

    package application;

    import javafx.application.Application;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.Parent;
    import javafx.scene.Scene;
    import javafx.stage.Stage;

    public class Main extends Application {
public void start(Stage primaryStage) {
    try {
        Parent root = FXMLLoader.load(getClass().getResource("/fxml/Main.fxml"));
        Scene scene = new Scene(root,600,400);
    } catch(Exception e) {

public static void main(String[] args) {

MainControl class:

    package application;

    import java.util.ResourceBundle;

    import javafx.event.ActionEvent;
    import javafx.fxml.FXML;
    import javafx.fxml.Initializable;
    import javafx.scene.control.Button;
    import javafx.scene.control.TextField;

    public class MainControl implements Initializable {
Button button;
TextField field1;
TextField field2;
boolean field1selected=true;
public void initialize(URL arg0, ResourceBundle arg1) {

public void switchTextFeild(ActionEvent event){
The code for switch on witch TextField is selected would go here


    <?xml version="1.0" encoding="UTF-8"?>

    <?import javafx.scene.text.*?>
    <?import javafx.scene.control.*?>
    <?import java.lang.*?>
    <?import javafx.scene.layout.*?>

    <AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="" xmlns:fx="" fx:controller="application.MainControl">
    <TextField fx:id="field1" layoutX="6.0" layoutY="2.0" prefHeight="394.0" prefWidth="149.0" />
    <TextField fx:id="field2" layoutX="445.0" layoutY="2.0" prefHeight="394.0" prefWidth="149.0" />
  <Button fx:id="button" layoutX="177.0" layoutY="14.0" mnemonicParsing="false" onAction="#switchTextFeild" prefHeight="95.0" prefWidth="239.0" text="Switch" textAlignment="CENTER" wrapText="true">
        <Font size="24.0" />
5/8/2015 2:05:10 AM

Accepted Answer

You can use


in your initialize() method, so your TextField field1 will be focused after your app is started. But notice, you have to wrap the requestFocus() call within a

Platform.runLater(new Runnable() {

            public void run() {

because this should be done on the JavaFX Application Thread and not on the Launcher Thread, so if you would only call field1.requestFocus() this wont have any effect on our TextField.

7/18/2014 9:56:32 AM

This is very simple


you have to first get the focus then use selectAll()function . if you will not use requestFocus() function then selectAll() will not work

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