labelFor field for a Label doesn't function as I expected

1.1k Views Asked by At

What exactly is the purpose of the labelFor field of the Label object?

Yesterday was the first time I have heard about this JavaFX thing, so I apologize if this sounds entirely silly. This word Label seems familiar to me from the one in HTML nodes. For this reason, I thought that the labelFor field would be similar to the for property of a label node. Unfortunately, it did not function as I had expected, at least I couldn't make it.

Here, let me make it clear with an example:

Label name = new Label("Your name:");
TextField nameField = new TextField();

name.setLabelFor(nameField);

Sorry that it is not really a MWE, but here's what I was expecting with this: Whenever the user clicks over the label name, the text field nameField shall receive the focus.

This, as far as I remember, is exactly what happens with the label/input pairs in HTML. On the other hand, nothing happens with the code given above in JavaFX.

I can patch it to make that happen by adding the following line after the other three:

name.setOnMouseClicked(event -> name.getLabelFor().requestFocus());

But then, why did I specify the labelFor in the first place?

1

There are 1 best solutions below

0
On

As stated in javadoc:

A Label can act as a label for a different Control or Node. This is used for Mnemonics and Accelerator parsing. This allows setting of the target Node.

So if you set a mnemonic for a label:

    Label label = new Label("_Text");
    label.setMnemonicParsing(true);
    label.setLabelFor(tf);

then using this mnemonic (Alt-T) will put focus into labeled Node.

Also labelFor will help disabled user who will be provided with a description on the control taken from the referred label.