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 fitWidthProperty
y fitHeightProperty
de la ImageView y atarlos al widthProperty
y heightProperty
del 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 setPreserveRatio
en 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);