FreeCode

Donate HTML/CSS JavaFX Java Home
JavaFX Starter Template JavaFX Labels JavaFX Buttons JavaFX Toggle Buttons JavaFX Radio Buttons and Toggle Groups JavaFX Checkboxes JavaFX Choice Boxes JavaFX Combo Boxes JavaFX Text Areas JavaFX Text Fields JavaFX List Views JavaFX Image Views JavaFX Color Pickers JavaFX Date Pickers JavaFX Resizable Split Pane Layouts JavaFX VBox (Vertical Box Layouts) JavaFX HBox (Horizontal Box Layouts) JavaFX Flow Pane Layouts JavaFX Tile Pane Layouts JavaFX Web Views

Labels in JavaFX

Code Description:

The code provided below shows how to create a Label in JavaFX. Labels are simply plain text that can be viewed on a user interface.

Label Syntax:

Label label = new Label("Label Text");

Runnable JavaFX Label Example Code:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Demo extends Application {

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

    @Override
    public void start(Stage primaryStage) throws Exception {
		
	VBox root = new VBox();
		
	Label label = new Label("This is a label...");
					
	root.getChildren().addAll(label);
		
	primaryStage.setTitle("Label Demo");
	primaryStage.setScene(new Scene(root, 200, 100));
	primaryStage.show();
		
    }

}

How to Run This Code:

Make sure that your Class name is the same as ours. In this case, we are using the Class name of "Demo". Alternatively, you can change the Class name in the provided code to match yours.

Note: You will NOT be able to copy and paste this code into your IDE unless you first set up JavaFX for your project. Check out this link if you need help setting up JavaFX:

JavaFX Comprehensive Setup Guide

Output:

JavaFX Label Output Image

Important Methods:

  • setText() - Used to set the current text of the label.
  • getText() - Used to get the current text of the label.
  • setPrefSize() - Set the preferred width and height for the label.
  • setFont() - Set the font and font size for the label text. EX: "label.setFont(new Font("Courier New", 20));"
  • setStyle() - Set an inline CSS-like style on the label. EX: "label.setStyle("-fx-background-color: green;");"
  • setTooltip() - Set a message that displays when a user hovers over the label for a certain amount of time. EX: "label.setTooltip(new Tooltip("Look at me!"));"
  • setVisible() - Show or hide a label from the scene. EX: "label.setVisible(false);"

Related Links:

a class="relatedLink" href="https://www.freecode.net/snippets_java/javafx_button.php">JavaFX Buttons JavaFX Text Areas JavaFX Text Fields