JavaFX Label setLabelFor() method example

In JavaFX, you can create a label by instantiating the javafx.scene.control.Label class. This class provides a method named labelFor(). Using this method, you can set the current label as a label for another control node.

This method comes handy while setting, mnemonics, and accelerator parsing.


In the following JavaFX example, we have created a label, a text field, and a button. Using the labelFor() method we have associated the label (Text) with a text field, enabling the mnemonic parsing (T). Therefore, on the output window, if you press Alt + t, the text field will be focused.

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class LabelFor_Example extends Application {
   public void start(Stage stage) {
      //Creating nodes
      TextField textField = new TextField();
      Button button = new Button("Click Me");
      //creating labels
      Label label1 = new Label("_Text");
      //Adding labels for nodes
      HBox box1 = new HBox(5);
      box1.setPadding(new Insets(25, 5 , 5, 50));
      box1.getChildren().addAll(label1, textField, button);
      //Setting the stage
      Scene scene = new Scene(box1, 595, 150, Color.BEIGE);
      stage.setTitle("JavaFX Example");
   public static void main(String args[]){