What i want to achieve:
我正在使用 FileChooser
,用户选择合适的 .jpg
图像文件。然后我复制该图像,将其重命名为 background.jpg
到已知文件夹并尝试使用 .setStyle(...);
将其设置为应用程序的背景图像> 复制图片没有问题[我正在检查]
The Problem that occurs:
我有一个带有 BorderPane
的舞台。 BorderPane
有一个背景 Image
,我使用
borderPane.setStyle("-fx-background-image:url('filepath')");
!第一次效果很好!
->然后我将删除该文件 [background.jpg] 并将其替换为另一个名为 [background.jpg] 的文件。 BorderPane
的背景图片没有改变....
我也尝试过再次使用相同的样式:
borderPane.setStyle("-fx-background-image:url('filepath')");
最后,当我更改文件名时,例如更改为 [background-12.jpg] 并使用上面的方法重置样式时,它会更改背景图像。
到底是什么问题?我的意思是我确信 background.jpg 已经创建,我正在检查它,而且当我一次又一次地将名称更改为其他名称时,它仍然有效。
Java CSS 解析器是否懒惰解析相同但具有其他 -fx-background-image
资源的新样式?
至于文件路径,我确定它很好,我使用下面的代码:
//Maou is the File URL in appropriate format for CSS
String maou = file.getAbsoluteFile().toURI().toString()
//Here i add the appropriate file separator, if not JavaFX will report error
maou = maou.replaceAll("\\Q\\\\E", "//");
//Print maou
System.out.println("Maou=\n" + maou);
Solution :
我发现使用 James_D answer 的最佳解决方案,稍作修改使其覆盖整个窗口:
BackgroundImage bgImg = new BackgroundImage(image, BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT,
new BackgroundSize(window.getWidth(), window.getHeight(), true, true, true, true));
最佳答案
与其使用内联样式,我建议通过 background
property 设置背景直接:
Image img = new Image(file.getAbsoluteFile().toURI().toString());
BackgroundImage bgImg = new BackgroundImage(img,
BackgroundRepeat.NO_REPEAT,
BackgroundRepeat.NO_REPEAT,
BackgroundPosition.DEFAULT,
BackgroundSize.DEFAULT);
borderPane.setBackground(new Background(bgImg));
Background
类提供 Java API 编程访问所有可由 CSS 设置的相同属性。
关于 `-fx-background-image` 更改时,JavaFX .setStyle(...) 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43614736/