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:
//Main.java
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) {
launch(args);
}
@Override
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);
primaryStage.setScene(scene);
// Show the window.
primaryStage.show();
}
}
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:
Flowchart:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/javafx/javafx-user-interface-components-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics