Adam Novakovi
Adam Novakovi

Reputation: 819

javafx moving FXML properties to a separateclass / bean

I've got a simple app that has its elements defined in .FXML file

<TextField fx:id="httpsPort" promptText="text1" GridPane.columnIndex="1" GridPane.rowIndex="1" />
<TextField fx:id="adminPort" promptText="text2" GridPane.columnIndex="1" GridPane.rowIndex="2" />

so far I was doing this

public class Controller {
    public TextField httpsPort;
    public TextField adminPort;

    //getters and setters here
}

but I'd like to be doing this in the controller

public class Controller {

    //maybe some magic annotation here
    public Layout layout;

    //the rest of the code
}


public class Layout {

    public TextField httpsPort;
    public TextField adminPort;

}

so basically, I'd like to separate properties that are connected to layout to another class either using some annotation, xml configuration, etc.. Is there any known way to achieve this?

Upvotes: 1

Views: 110

Answers (1)

James_D
James_D

Reputation: 209408

Use <fx:include>:

ports.fxml:

<GridPane fx:controller="com.mycompany.Layout">

    <TextField fx:id="httpsPort" promptText="text1" GridPane.columnIndex="1" GridPane.rowIndex="1" />
    <TextField fx:id="adminPort" promptText="text2" GridPane.columnIndex="1" GridPane.rowIndex="2" />

</GridPane>

and then main.fxml:

< ... fx:controller="com.mycompany.MainController">
    <!-- ... -->
    <fx:include fx:id="layout" source="ports.fxml"/>
    <!-- ... -->

Your MainController can do:

public class MainController {

    @FXML
    private Layout layoutController ; // field name is fx:id with "Controller" appended

}

and the Layout is

public class Layout {

    @FXML
    private TextField httpsPort;
    @FXML
    private TextField adminPort;

}

See the documentation section on Nested Controllers (or dozens of similar questions on this site) for more details.

Upvotes: 1

Related Questions