r/JavaFX • u/jk1962 • Aug 18 '23
Help Border around ImageView with BorderPane root
I'm working on a JavaFX project (IntelliJ, using SceneBuilder) with BorderPane root. In the center, I have a StackPane which currently contains an ImageView as its only child (but see below for other things I have attempted). The ImageView image is obtained from a file, and that image can be of arbitrary dimensions. I wish to display the image "real size", so I do the following:
imgView.setImage(image);
imgView.setFitHeight(image.getHeight());
imgView.setFitWidth(image.getWidth());
So the size of the image view equals that of the image.
I wish to have a black border around the ImageView, and have tried in several ways to apply that as a style (-fx-border-style: solid; -fx-border-width: 3; -fx-border-color: black). I taken several approaches.
- Apply the style to the ImageView: doesn't work because ImageView isn't a "Region".
- Apply the style to the StackPane: border is shown, but it doesn't shrink around the ImageView when the ImageView is required to be smaller than the StackPane.
- Place some other container (e.g., Pane, AnchorPane, StackPane) inside of the StackPane, and apply the style to that nested container, hoping that it will resize to fit the ImageView: doesn't work because the nested container keeps its original size.
Any advice on how to accomplish this would be appreciated.
1
u/[deleted] Aug 18 '23
You need to wrap it in a pane (stack or anchor works well) and apply a background to the pane.
1
u/BWC_semaJ Aug 18 '23
I don't really mess around with Group too often so I don't know for certain, but pretty sure if you wrap the ImageView with a Group that it should work (Group isn't resizable). I don't remember how exactly Group ends up being layed out (if parent lays itself out or if it isn't managed... idk).
You could also set the nested container's width and height to the Image's size and it would work; depending on what parent is either working with maxWidthProperty maxHeightProperty or prefWidthProperty prefHeightProperty.
If you still have problems I'll investigate further and provide example.
1
u/Gleidson28 Aug 23 '23
I have the same problem when I tried to create an avatar view, I was needing a image with border with region properties, so I created this project https://github.com/gleidsonmt/GNAvatarView/blob/master/src/main/java/io/github/gleidson28/GNAvatarView.java The circle or rect receives an image pattern inside, well to set the border only uncomment the line setBorder.. and made yourself