JavaFX
provides setOn* methods to receive events from the user interactions.
For
example, below snippet set the text of label when user clicks on the button.
button.setOnAction((ActionEvent
e) -> {
label.setText("You clicked");
});
Find the
below working application.
package com.sample.demos; import static javafx.geometry.Pos.CENTER; import java.io.FileNotFoundException; import javafx.application.Application; import javafx.event.ActionEvent; 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 ButtonApp extends Application { @Override public void start(Stage primaryStage) throws FileNotFoundException { Button button = new Button("Click Me"); Label label = new Label(); VBox vBox = new VBox(10, button, label); vBox.setAlignment(CENTER); Scene scene = new Scene(vBox, 400, 400); button.setOnAction((ActionEvent e) -> { label.setText("You clicked"); }); /* Set the scene to primaryStage, and call the show method */ primaryStage.setTitle("JavaFX Button Example"); primaryStage.setScene(scene); primaryStage.show(); } }
TestFX.java
package com.sample.demos; import javafx.application.Application; public class TestFX { public static void main(String args[]) { Application.launch(ButtonApp.class, args); } }
When you ran above application, you can able to see below window.
When you
click on the button ‘Click Me’, the window adds label to the content pane.
No comments:
Post a Comment