Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FXML: An elegant way to bind a child width/height to the parent's width/height

Tags:

javafx

fxml

I'm using FXML with JavaFX to develop graphical interfaces. I discovered this method for binding the width/height of a child node to the width/height of it's parent node:

<Node fx:id="parent">
    <children>
        <Node prefWidth=${parent.width}></Node>
    <children>
</Node>

But that feels inelegant. I'd rather not have to give an id to a node just so it's child can reference it's dimensions. Is there perahps some method for referenceing the parent of a node? Maybe something like prefWidth=${parent.width}?

NOTE: I know this can be done programmatically from Java, but that's not what I want here. I'm looking for a way to do this in the FXML.

like image 239
J-bob Avatar asked Oct 21 '16 16:10

J-bob


People also ask

What is@ FXML annotation?

The @FXML annotation enables an FXMLLoader to inject values defined in an FXML file into references in the controller class.

What is the FXML file?

FXML is an XML-based user interface markup language created by Oracle Corporation for defining the user interface of a JavaFX application. FXML presents an alternative to designing user interfaces using procedural code, and allows for abstracting program design from program logic.


1 Answers

Expression bindings work by referencing elements of the FXMLLoader's namespace. There is no concept of "this" to refer to "the current node" (that I am aware of). So the only way to access the parent of a node is for the node itself to be part of the namespace: you can achieve this by setting an fx:id on the node itself:

<Pane>
    <children>
        <Node fx:id="node" prefWidth="${node.parent.width}"></Node>
    <children>
</Pane>
like image 136
James_D Avatar answered Sep 29 '22 21:09

James_D