具有多种颜色的JavaFX警报

问题描述 投票:0回答:1

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

但是我想知道是否有一种方法--使用css--只显示一个红色和橙色的警告。

下面是我想实现的一个例子(这两个警告可以分开成 "部分")。

RED ERROR1
RED ERROR2
RED ERROR3
ORANGE WARNING1
ORANGE WARNING2

我看到一些答案指向 RichTextFX 像这样然而,我不明白(或者说不知道)这怎么能适用于通用的Alerts。如果不写一些自定义的 ExpandedAlert 类?

css javafx alert
1个回答
3
投票

Alert 类继承自 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();
    }

}

它给出了这个结果。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.