简体   繁体   中英

JavaFX Alert with multiple colors

I have a program that at some point (may) displays two warnings - one about errors - those are in red, and one about warnings - those are in orange.

I wonder however if there is a way - using css - to have just one warning with some text red and some text orange.

Here is an example of what I want to achieve (the two can be separated into "sections"):

RED ERROR1
RED ERROR2
RED ERROR3
ORANGE WARNING1
ORANGE WARNING2

I've seen some answers pointing to RichTextFX like this one , however I don't see (or don't know) how that could apply to generic Alerts. Is that even possible, without writing some custom ExpandedAlert class?

The Alert class inherits from Dialog , which provides a pretty rich API and allows arbitrarily complex scene graphs to be set via the content property.

If you just want static text with different colors, the simplest approach is probably to add labels to a VBox ; though you could also use more complex structures such as TextFlow or the third-party RichTextFX mentioned in the question if you need.

A simple example is:

import java.util.Random;

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

public class App extends Application {

    private final Random rng = new Random();

    private void showErrorAlert(Stage stage) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        int numErrors = 2 + rng.nextInt(3);
        int numWarnings = 2 + rng.nextInt(3);
        VBox errorList = new VBox();
        for (int i = 1 ; i <= numErrors ; i++) {
            Label label = new Label("Error "+i);
            label.setStyle("-fx-text-fill: red; ");
            errorList.getChildren().add(label);
        }
        for (int i = 1 ; i <= numWarnings ; i++) {
            Label label = new Label("Warning "+i);
            label.setStyle("-fx-text-fill: orange; ");
            errorList.getChildren().add(label);
        }
        alert.getDialogPane().setContent(errorList);
        alert.initOwner(stage);
        alert.show();
    }
    @Override
    public void start(Stage stage) {
        Button showErrors = new Button("Show Errors");
        showErrors.setOnAction(e -> showErrorAlert(stage));
        BorderPane root = new BorderPane(showErrors);
        Scene scene = new Scene(root, 400, 400);
        stage.setScene(scene);
        stage.show();
    }


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

}

which gives this result:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM