Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change fxml lable text by id

I have Label on my fxml file:

 <children>
    <Label fx:id="lblTest" text="Label" />
 </children>

How can i change the text from "Label" to "Hello" from the main/controller java file?

I just started to learn the basics of JavaFX and i am not sure if it possible

like image 254
Oshrib Avatar asked Sep 27 '15 08:09

Oshrib


1 Answers

Problem

You want to set the text on a label that is part of FXML/Controller/MainApp

Solution

Normally you have three files:

  1. FXML-Document
  2. FXML-Controller
  3. Class that extends Application and overrides the start method

A little Example:

LabelText.java

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class LabelText extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

FXMLDocument.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.40" fx:controller="labeltext.FXMLDocumentController">
    <children>
        <Label fx:id="lblTest" layoutX="126.0" layoutY="92.0" minHeight="16" minWidth="69" />
    </children>
</AnchorPane>

FXMLDocumentController.java

package labeltext;

import javafx.fxml.FXML;
import javafx.scene.control.Label;

public class FXMLDocumentController {

    @FXML
    private Label lblTest;

    @FXML
    private void initialize() {
        lblTest.setText("I'm a Label.");
    }
}

And that's it.

like image 118
aw-think Avatar answered Oct 25 '22 07:10

aw-think