您可以在将颜色应用到堆栈窗格之前简单地验证颜色。如果颜色不是有效颜色,则设置默认颜色。
下面是一个将十六进制颜色值应用于堆栈窗格的简单示例。颜色值存储在组合框中。现在,在将背景颜色设置为 stackpane 之前,我调用了一个方法 getColorValue(String colorValue)。现在,如果颜色是有效颜色,那么我设置颜色,否则我打印一条消息并设置默认颜色。以下示例中的默认颜色为红色 (#F00000)。
为了验证颜色,我使用了正则表达式。
private static final String HEX_PATTERN = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$";
正则表达式很简单。它查找由 [A-Fa-f0-9]{6} 表示的 6 个字母值或由 [A-Fa-f0-9]{3} 表示的 3 个字母值。颜色值必须以“#”符号开头。
public class ColorApp extends Application {
String backGroundColor = "";
@Override
public void start(Stage primaryStage) throws Exception {
Label messageLabel = new Label("Color NOT SELECTED FROM COMBOBOX");
ObservableList<String> options =
FXCollections.observableArrayList(
"DEFG",
"#ZZZAAA",
"#ABCDEF",
"#055"
);
StackPane stackPane = new StackPane();
final ComboBox comboBox = new ComboBox(options);
comboBox.setItems(options);
stackPane.getChildren().addAll(messageLabel,comboBox);
StackPane.setAlignment(messageLabel,Pos.TOP_LEFT);
comboBox.valueProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue observable, String oldValue, String newValue) {
backGroundColor = newValue;
stackPane.styleProperty().setValue("-fx-background-color: " + (backGroundColor = ColorUtils.getColorValue(backGroundColor)) + ";");
messageLabel.setText(backGroundColor + " Applied");
}
});
Scene scene = new Scene(stackPane,600,800);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
class ColorUtils {
private static final String HEX_PATTERN = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$";
static Pattern pattern = Pattern.compile(HEX_PATTERN);
static Matcher matcher;
private static final String DEFAULT_COLOR_VALUE = "#F00000";
public static String getColorValue(String colorValue) {
matcher = pattern.matcher(colorValue);
boolean result = matcher.matches();
if (result == false) {
System.out.println("Invalid colorValue detected, colorValue==" + colorValue);
System.out.println("Setting default Color Value to RED");
return DEFAULT_COLOR_VALUE;
} else {
return colorValue;
}
}
}
如果从组合框中选择的颜色得到验证,将显示以下输出。
颜色验证:
颜色未验证:
编辑:请注意,我正在使用堆栈窗格并手动将位置设置为标签。不建议这样做。仅用于演示目的。