使用 javafx 在运行时更改背景图像

changing background image in runtime with javafx

我想将窗格的背景图像设置为用户通过 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);

使用此方法将 RegionBackground 设置为给定的图像 File:

static void setBackgroundImage(File file, Region region) throws MalformedURLException {
    Image image = new Image(file.toURI().toURL().toExternalForm());
    region.setBackground(new Background(new BackgroundImage(
            image,
            BackgroundRepeat.NO_REPEAT,
            BackgroundRepeat.NO_REPEAT,
            BackgroundPosition.CENTER,
            BackgroundSize.DEFAULT
    )));

}

或者,对于拉伸到 Region 大小的图像,使用 BackgroundFillImagePattern:

region.setBackground(new Background(new BackgroundFill(new ImagePattern(image), CornerRadii.EMPTY, Insets.EMPTY)));