5

I have a TextField and a Label with mnemonicParsing true. I want to set the labelFor property of the label with the id of the TextField. How do I do that in FXML?

<GridPane hgap="5.0" snapToPixel="false" vgap="10.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<children>
      <Label maxWidth="-Infinity" text="_A Label" GridPane.halignment="RIGHT" GridPane.hgrow="NEVER" GridPane.vgrow="NEVER" mnemonicParsing="true" />
      <TextField id="myTextField" GridPane.columnIndex="1" GridPane.hgrow="NEVER" />
</children>
</GridPane>

Thanks

Paul
  • 275
  • 1
  • 2
  • 13

2 Answers2

5

You can use the dollar notation:

<GridPane hgap="5.0" snapToPixel="false" vgap="10.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
    <children>
          <Label labelFor="$myTextField" maxWidth="-Infinity" text="_A Label" GridPane.halignment="RIGHT" GridPane.hgrow="NEVER" GridPane.vgrow="NEVER" mnemonicParsing="true"  />
          <TextField id="myTextField" GridPane.columnIndex="1" GridPane.hgrow="NEVER" />
    </children>
</GridPane>
Puce
  • 37,247
  • 13
  • 80
  • 152
  • 2
    I think `id="myTextField"` should be `fx:id="myTextField"` here – SWdV Jun 23 '18 at 13:53
  • 3
    I found that for me this only works if the referenced node (TextField) is declared *before* the label that references it in the FXML file. – Gerhard Jul 07 '19 at 08:50
4

If found the solution...

<GridPane hgap="5.0" snapToPixel="false" vgap="10.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<children>
      <Label maxWidth="-Infinity" text="_A Label" GridPane.halignment="RIGHT" GridPane.hgrow="NEVER" GridPane.vgrow="NEVER" mnemonicParsing="true">
           <labelFor>
               <TextField id="myTextField" GridPane.columnIndex="1" GridPane.hgrow="NEVER" />
           </labelFor>
      </Label>
      <fx:reference source="myTextField" />
</children>
</GridPane>
Paul
  • 275
  • 1
  • 2
  • 13