具有多种颜色的 JavaFX 警报

JavaFX Alert with multiple colors

我有一个程序在某些时候(可能)显示两个警告 - 一个关于错误 - 红色,另一个关于警告 - 橙色。

不过,我想知道是否有一种方法 - 使用 css - 只发出一个带有红色文本和橙色文本的警告。

下面是我想实现的例子(两者可以分开"sections"):

RED ERROR1
RED ERROR2
RED ERROR3
ORANGE WARNING1
ORANGE WARNING2

我看到一些答案指向 RichTextFX like this one,但是我没有看到(或不知道)如何将其应用于通用警报。如果不编写一些自定义 ExpandedAlert class?

甚至有可能吗?

Alertclass继承自Dialog,提供了相当丰富的API,允许通过content设置任意复杂的场景图属性。

如果您只想要具有不同颜色的静态文本,最简单的方法可能是向 VBox 添加标签;尽管您也可以使用更复杂的结构,例如 TextFlow 或问题中提到的第三方 RichTextFX,如果您需要的话。

一个简单的例子是:

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();
    }

}

结果如下: