How to set an image to the size of a button in JavaFX

J.erome :

I'm using JavaFX for school and I need to display a picture on a button when I click on it. My problem is that the image is bigger than the button and then everything is horrible. I have seen multiples post on how to fit a image to a button and I came with that code

Image imageOk = new Image(getClass().getResourceAsStream("/TP2/ressources/flag.png"));
ImageView img = new ImageView(imageOk);
img.setFitWidth(100);
img.setFitHeight(100);
btn.setGraphic(img);

When I create the button I use setPrefSize(50, 50);

Samuel Philipp :

You can use the fitWidthProperty and fitHeightProperty of the ImageView and bind them to the widthProperty and heightProperty of the button:

img.fitWidthProperty().bind(btn.widthProperty());
img.fitHeightProperty().bind(btn.heightProperty());

This will cause the ImageView to have the same size as the button every time.

This can cause the image to be stretched. To prevent this you can use setPreserveRatio on the image:

img.setPreserveRatio(true);

Here is the complete example code:

Button btn = new Button();
btn.setPrefSize(50, 50);
Image imageOk = new Image(getClass().getResourceAsStream("yes.png"));
ImageView img = new ImageView(imageOk);
img.setPreserveRatio(true);
img.fitWidthProperty().bind(btn.widthProperty());
img.fitHeightProperty().bind(btn.heightProperty());
btn.setGraphic(img);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=81756&siteId=1