我有一个程序,该程序有时(可能)显示两个警告-一个关于错误-红色,另一个关于警告-橙色。
但是我想知道是否有一种方法-使用CSS-仅发出一个警告,带有一些红色的文本和一些橙色的文本。
以下是我要实现的示例(两者可以分成“小节”):
BackgroundWorker
我已经看到一些指向RED ERROR1
RED ERROR2
RED ERROR3
ORANGE WARNING1
ORANGE WARNING2
like this one的答案,但是我看不到(或不知道)这如何适用于通用警报。无需编写一些自定义RichTextFX
类,是否有可能?
答案 0 :(得分: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();
}
}
给出以下结果: