语句 1 从 css 获取图像文件,但无法找到图像文件,即使我提供了绝对 url。为什么?
图像文件位置是正确的,因为在语句 3 中它有效。 这是对 solution 的进一步查询由 Jewelsea 发布。
import javafx.scene.image.Image;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class TextFieldCssSample extends Application {
@Override
public void start(Stage stage) {
TextField textField = new TextField();
textField.setId("textField");
StackPane layout = new StackPane();
layout.getChildren().addAll(textField);
// 1) following statement **fails**. resources folder is below the root level folder
textField.setStyle("-fx-border-color: red; -fx-background-image:url('/resources/pumpkin-icon.png'); -fx-background-repeat: no-repeat; -fx-background-position: right center;");
// 2) following statement succeeds in finding a http url.
// textField.setStyle("-fx-border-color: red; -fx-background-image:url('http://icons.iconarchive.com/icons/rockettheme/halloween/32/pumpkin-icon.png'); -fx-background-repeat: no-repeat; -fx-background-position: right center;");
// 3) following statement succeeds finding image file.
stage.getIcons().add(new Image("/resources/pumpkin-icon.png"));
stage.setScene(new Scene(layout));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
更新:cnahr 的解决方法有效!我还打开了 JavaFX 错误报告。RT-31131
最佳答案
省略内联 CSS URL 中的前导斜杠。
说真的。我只是尝试了一下,发现只有当 完整 URL 被指定为内联 CSS 中的相对 URL(如 (1))时,嵌入 JAR 中的图像才会加载.
但是,当我使用 (3) 中的图像构造函数时,我可以省略或包含前导斜杠。不管怎样,图像都会加载得很好。
所以我认为您刚刚在 JavaFX CSS 解析器中发现了一个错误。 :)
注:RT-31131 Inline CSS statement in Java FX2 code can't find the image file when absolute path is used作为 RT-21697 CSS: Absolute paths in url("...") without a scheme should be relative to the classpath 的重复项被关闭,该问题已在 Java 8 版本中得到解决,因此 CSS 处理错误已在后续 JavaFX 版本中得到修复。
关于javafx-2 - 为什么Java FX2代码中的这个css语句找不到图像文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17113887/