Cómo establecer una imagen al tamaño de un botón en JavaFX

J.erome:

Estoy usando JavaFX para la escuela y tengo que mostrar una imagen en un botón cuando hago clic en él. Mi problema es que la imagen es más grande que el botón y entonces todo es horrible. He visto múltiplos post sobre cómo ajustar una imagen a un botón y que llegó con ese código

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

Cuando creo el uso botón I setPrefSize(50, 50);

Samuel Philipp:

Puede utilizar la fitWidthPropertyy fitHeightPropertyde la ImageView y atarlos al widthPropertyy heightPropertydel botón:

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

Esto hará que el ImageView a tener el mismo tamaño que el botón cada vez.

Esto puede hacer que la imagen se estire. Para evitar esto se puede utilizar setPreserveRatioen la imagen:

img.setPreserveRatio(true);

Aquí está el código de ejemplo completo:

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

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=191328&siteId=1
Recomendado
Clasificación