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

5

我正在学校使用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);。该方法可以设置按钮的首选大小为50x50像素。
1个回答

3
你可以使用 ImageView 的 fitWidthProperty 和 fitHeightProperty,并将它们绑定到按钮的 widthProperty 和 heightProperty 上:
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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接