如何在JavaFX中将图像设置为按钮大小

时间:2019-03-15 15:25:15

标签: java image button javafx

我在学校使用JavaFX,单击时需要在按钮上显示图片。我的问题是图像大于按钮,然后一切都变得可怕。我见过有关如何使图像适合按钮的多个文章,而我附带了该代码

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

创建按钮时,我使用setPrefSize(50, 50);

1 个答案:

答案 0 :(得分:2)

您可以使用ImageView的fitWidthPropertyfitHeightProperty并将它们绑定到按钮的widthPropertyheightProperty

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

这将导致ImageView每次具有与按钮相同的大小。

这可能会导致图像拉伸。为防止这种情况,您可以在图像上使用setPreserveRatio

img.setPreserveRatio(true);

这是完整的示例代码:

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