HIDE NAV

JavaFX Clickable Controls

This program shows how to make control items run code when clicked.

Main.java


package ceccs;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class ClickablesJFX extends Application {
    public static void main(String[] args){
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Label infoLabel = new Label("Click Something.");

        Button btn = new Button("Click This!");
        btn.setOnAction(event -> {
            System.out.println("System Print fromm Btn");
            infoLabel.setText("You clicked tha button.");
        });

        Rectangle box = new Rectangle(80,30, Color.BLUE);
        box.setOnMouseClicked(event -> {
            System.out.println("System Print fromm that blue box");
            infoLabel.setText("You clicked The BOX.");
        });
        infoLabel.setOnMouseClicked(event -> {
            System.out.println("Label Clicked, clearing text.");
            infoLabel.setText("");
        });

        /** make a layout for the buttins*/
        VBox outerCol = new VBox();
        HBox innerRow = new HBox();
        outerCol.setPadding(new Insets(10, 40, 10, 40));
        outerCol.setAlignment(Pos.CENTER);
        outerCol.setSpacing(15);
        innerRow.setAlignment(Pos.CENTER);
        innerRow.setSpacing(40);
        outerCol.getChildren().add(infoLabel);
        outerCol.getChildren().add(innerRow);
        innerRow.getChildren().add(btn);
        innerRow.getChildren().add(box);

        Scene scene = new Scene(outerCol);
        primaryStage.setScene(scene);
        primaryStage.show();



    }
}