Using JavaFX: Is It Possible to Put A GridPane in an Alert Dialog Box?

1.8k views Asked by At

I have an alert box that is populated with text and for formatting reasons I was wondering if I could somehow put a GridPane inside this Alert box so all the text is spaced out correctly.

If it is not possible to do this with GridPane is there some other way of formatting text I could use?

1

There are 1 answers

0
jewelsea On BEST ANSWER

Yes, you can set any node as content of a dialog box.

alert.getDialogPane().setContent(grid);

Here is a sell/buy alert for frozen orange contracts formatted as grid content.

frozen orange juice contracts

import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Modality;
import javafx.stage.Stage;

public class GridAlert extends Application {
    @Override
    public void start(Stage stage) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setHeaderText("Frozen Orange Juice Contracts");

        GridPane grid = new GridPane();
        grid.addRow(0, new Label("Sell"), new Label("142"));
        grid.addRow(1, new Label("Buy"), new Label("29"));
        grid.setHgap(30);
        ColumnConstraints right = new ColumnConstraints();
        right.setHalignment(HPos.RIGHT);
        grid.getColumnConstraints().setAll(new ColumnConstraints(), right);

        alert.getDialogPane().setContent(grid);

        Button showAlert = new Button("Show Alert");
        showAlert.setOnAction(event -> alert.showAndWait());

        HBox layout = new HBox(10);
        layout.getChildren().addAll(
                showAlert
        );
        layout.setPadding(new Insets(10));
        stage.setScene(new Scene(layout));
        stage.show();

        alert.initOwner(stage);
        alert.initModality(Modality.WINDOW_MODAL);
    }

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