JavaFX Button label text change

JavaFx User Interface Components: Exercise-1 with Solution

Write a JavaFX application with a button that changes the label text when clicked. Initially, the label should display "JavaFX!" When the button is clicked, change the label text to "Button Clicked!".

Sample Solution:

JavaFx Code:


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

public class Main extends Application {

    public static void main(String[] args) {

    public void start(Stage primaryStage) {
        primaryStage.setTitle("Button Label App");

        // Create a label with the initial text.
        Label label = new Label("JavaFX!");

        // Create a button.
        Button button = new Button("Click Me");

        // Set an action for the button to change the label text.
        button.setOnAction(event -> {
            label.setText("Button Clicked!");

        // Create a layout (VBox) to arrange the label and button.
        VBox root = new VBox(10);
        root.getChildren().addAll(label, button);

        // Create the scene and set it in the stage.
        Scene scene = new Scene(root, 300, 200);

        // Show the window.

In the above JavaFX application, we create a label with the initial text "JavaFX!" and a button labeled "Click Me." When the button is clicked, we use an event handler to change the label's text to "Button Clicked!" The label and button are arranged in a VBox layout, and the whole scene is displayed in a window.

Sample Output:

JavaFx: JavaFX Button label text change
JavaFx: JavaFX Button label text change


Flowchart: JavaFX Button label text change.

Java Code Editor:

Previous: JavaFx User Interface Components Exercises Home.
Next: JavaFX two buttons label change.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.