Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javafx 2 通过javafx代码(非css)设置背景图像_Javafx 2 - Fatal编程技术网

Javafx 2 通过javafx代码(非css)设置背景图像

Javafx 2 通过javafx代码(非css)设置背景图像,javafx-2,Javafx 2,我正在尝试使用以下代码将图像设置为背景: root.setStyle("-fx-background-image: url('splash.jpg'); -fx-background-position: center center; -fx-background-repeat: stretch;"); 但它不起作用。如果我用CSS设置它,它会完美工作: root.setId("pane"); primaryStage.getSce

我正在尝试使用以下代码将图像设置为背景:

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
上找到详细的文档


(很抱歉回答这个老问题。)

这只是为我创建了一个空白的VBox:@JoshDiamond在我看来,
新图像(…)
的构造函数的url在您的代码中可能不正确。您是否尝试过改用
getResource(…)