How do I add margin or padding for ImageView in JavaFX using code (not FXML)?

I want to add a white border around the ImageView.

One solution is to use a Button.

Button group

Tried using StackPane:

StackPane stackPaneforImageActivity = new StackPane();

    Image activityImage = new Image(file.toURI().toString());
    ImageView imv = new ImageView(activityImage);

    newActivityHBox.getChildren().add(stackPaneforImageActivity);

    stackPaneforImageActivity.getChildren().add(imv);

    stackPaneforImageActivity.setPadding(new Insets(10));

    stackPaneforImageActivity.setStyle("-fx-border-color:white;-fx-background-color: black;");

    imv.setFitHeight(30);
    imv.setFitWidth(30);

newActivityHBox.getChildren().add(imv);

Using StackPane

But as a result, the image goes beyond the StackPane.

What is the reason for this?

Is there another option to make a border around the image?

Author: Sidachenko Michael, 2018-05-10

1 answers

The reason is the last line of code that I didn't immediately notice.

It turns out that I added the ImageView to the layout twice. Once per StackPane:

stackPaneforImageActivity.getChildren().add(imv);

And the second time in HBox:

newActivityHBox.getChildren().add(imv);

Only the last line worked.

It is not clear why there is no image in the StackPane.

The final version of the code looks like this:

Image activityImage = new Image(file.toURI().toString());
            ImageView imv = new ImageView(activityImage);

        StackPane stackPaneforImageActivity = new StackPane();

        stackPaneforImageActivity.setAlignment(Pos.CENTER);

        newActivityHBox.getChildren().add(stackPaneforImageActivity);

        stackPaneforImageActivity.getChildren().add(imv);

        stackPaneforImageActivity.setPadding(new Insets(0,10,0,10));

        stackPaneforImageActivity.setStyle("-fx-border-color:white;-fx-background-color: black;");

        imv.setFitHeight(30);
        imv.setFitWidth(30);

A white border around the image is added.

 0
Author: Sidachenko Michael, 2018-05-13 17:04:57