【发布时间】:2016-04-06 00:26:30
【问题描述】:
问题
我想在我的 JavaFX GUI 中设置背景图像。 GUI 应该可以调整到任何比例,这样我的背景图像必须在两个方向上拉伸(同时改变背景图像的宽度和高度之间的比例)
受another stackoverflow post 启发,我通过 css 了解了如何做到这一点:
.root {
-fx-background-image: url('http://icons.iconarchive.com/icons/iconka/meow/256/cat-box-icon.png');
-fx-background-size: stretch;
}
但我有约束,我的背景图片是动态创建的作为BufferedImage。
第一种方法
因此我开始通过代码而不是 css 设置我的背景图像,如下所示:
Region region = // ...
BufferedImage bufferedBackgroundImage = // ...
WritableImage fxImage = new WritableImage(bufferedBackgroundImage.getWidth(), bufferedBackgroundImage.getHeight());
SwingFXUtils.toFXImage(bufferedBackgroundImage, fxImage);
region.setBackground(
new Background(
new BackgroundImage(
fxImage,
BackgroundRepeat.NO_REPEAT,
BackgroundRepeat.NO_REPEAT,
BackgroundPosition.DEFAULT,
new BackgroundSize(BackgroundSize.AUTO, BackgroundSize.AUTO, false, false, false, true))));
不幸的是,我的背景不再伸展了。 我在 BackgroundSize 和几个 BackgroundRepeat 常量中尝试了几种布尔值组合,但我只能在一个方向而不是两个方向上拉伸我的背景图像。
第二种方法
我尝试使用第一种方法的代码设置背景图像,然后添加样式表
region.setStyle("-fx-background-size: stretch;");
但随后背景图像完全消失了。我认为这是因为setStyle 而不是addStyle 所以我覆盖了它。
以下代码也不能正常工作。我认为是因为您只能将 URL 设置为 css 文件,但不能设置样式。
region.getStylesheets().add("-fx-background-size: stretch;");
问题
如果我能更进一步,我将不胜感激。
【问题讨论】:
标签: java user-interface javafx-8