Working with the fx:root attribute and custom components

You can revert the workflow of the FXML node creation and inject FXML content into your own object. This is especially useful if you want to create custom controls with content managed by FXML.

Firstly, the fx:root attribute should be used instead of the direct class name for the root node:

<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<fx:root type="HBox" xmlns:fx="http://javafx.com/fxml">
<children>
<Label fx:id="label" />
<TextField fx:id="textField" />
</children>
</fx:root>

Also, note that you may not set fx:controller here and select the desired type of the root.

Now, we can create the class that will be used as a root for such FXML:

// chapter4/fxroot/MyControl.java
public class MyControl extends HBox {

@FXML
private TextField textField;

@FXML
private Label label;

public MyControl(String text) throws IOException {
// here we initialize our HBox
setAlignment(Pos.CENTER);
setSpacing(5);

// loading FXML and using current object as it's root and controller
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("MyControl.fxml"));
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
fxmlLoader.load();

// now we already can use @FXML initialized controls
textField.setText(text);
label.setText("Message: ");
}
}

Here, we are using the same class for the Controller and Root, which allows us to contain all logic in one place. So, we can create our new control like a regular JavaFX class:

// chapter4/fxroot/FxRootDemo.java
public class FxRootDemo extends Application {

@Override
public void start(Stage stage) throws Exception {
StackPane stackPane = new StackPane();
stackPane.getChildren().add(
new MyControl("Hello, World"));
Scene scene = new Scene(stackPane, 300, 80);

stage.setScene(scene);
stage.show();
}
}

And, we will get the following application:

Note that your own controls can be used in FXML as well. You just need to provide the correct includes.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.215.96