我正在尝试使用以下代码将图像设置为背景:
root.setStyle("-fx-background-image: url('splash.jpg');
-fx-background-position: center center;
-fx-background-repeat: stretch;");
但它不起作用。如果我用CSS设置它,它会完美工作:
root.setId("pane");
primaryStage.getScene().getStylesheets().add(JavaFXApplication9.class.getResource("style.css").toExternalForm());
和CSS:
#pane{
-fx-background-image: url('splash.jpg');
-fx-background-repeat: stretch;
-fx-background-position: center center;
}
我的所有文件(主类、CSS和图像)都放在同一个包中。
那么,如何使用代码设置背景图像呢?或者,如何从应用程序代码中覆盖(替换)CSS中某个元素的背景图像行?谢谢
尝试下一步:
String image = JavaFXApplication9.class.getResource("splash.jpg").toExternalForm();
root.setStyle("-fx-background-image: url('" + image + "'); " +
"-fx-background-position: center center; " +
"-fx-background-repeat: stretch;");
如果您真的不想使用CSS或setStyle()
方法,可以使用以下方法:
// new Image(url)
Image image = new Image(CurrentClass.class.getResource("/path/to/package/bg.jpg"));
// new BackgroundSize(width, height, widthAsPercentage, heightAsPercentage, contain, cover)
BackgroundSize backgroundSize = new BackgroundSize(100, 100, true, true, true, false);
// new BackgroundImage(image, repeatX, repeatY, position, size)
BackgroundImage backgroundImage = new BackgroundImage(image, BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.CENTER, backgroundSize);
// new Background(images...)
Background background = new Background(backgroundImage);
您可以在此处找到有关BackgroundImage
的详细文档。
(很抱歉回答这个老问题。)