yukashima huksay
yukashima huksay

Reputation: 6238

changing background image in runtime with javafx

I want to set the background image of a pane to the image that the user chooses via a filechooser in javafx. Does anyone know how to do this? Here is my code:

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

Upvotes: 0

Views: 623

Answers (1)

fabian
fabian

Reputation: 82461

Use this method to set the Background of a Region to a image given as 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
    )));

}

Alternatively for a image streched to the size of the Region use a BackgroundFill with ImagePattern:

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

Upvotes: 1

Related Questions