0
我想將窗格的背景圖像設置爲用戶通過javafx中的filechooser選擇的圖像。有誰知道如何做到這一點? 這裏是我的代碼:使用javafx在運行時更改背景圖像
ImageView backgroundImageView = new ImageView();
backgroundImageView.setId("backgroundImageView");
FileChooser fileChooser = new FileChooser();
fileChooser.setInitialDirectory(new File(new File("src\\backgrounds").getAbsolutePath()));
fileChooser.setTitle("select background image");
Button openButton = new Button("select background image...");
openButton.setOnAction(
e -> {
File file = fileChooser.showOpenDialog(main.getPrimaryStage());
if (file != null) {
try {
root.setStyle("-fx-background-image: url(\'" + file.toURI().toURL().toString() + "\');-fx-background-position: center center;-fx-background-repeat: stretch;");
//root.setBackground(new Background(new BackgroundImage(new Image(file.toURI().toURL().toString()))));//terrible errors!
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
}
});
vBox.getChildren().add(openButton);