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

时间:2016-06-10 13:56:40

标签: java javafx background runtime

我想将窗格的背景图像设置为用户通过javafx中的filechooser选择的图像。有谁知道如何做到这一点? 这是我的代码:

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);

1 个答案:

答案 0 :(得分:1)

使用此方法将Background的{​​{1}}设置为Region的图像:

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的{​​{1}}:

BackgroundFill