我想使用FXML包含带有图标和文本的按钮。
我知道在FXML中可以使用以下代码添加图像:
<ImageView id="boxImage" fitWidth="100" fitHeight="100">
<image>
<Image url="@/com/example/app/resources/icons/office.png" />
</image>
</ImageView>
但我想知道如何将其与按钮代码合并:
<Button text="DATE"/>
真的很欢迎任何帮助或示例,因为我完全不知道如何使用FXML应用图像。
编辑
我做了以下回答:
<Button text="INSTRUMENT" styleClass="">
<graphic>
<ImageView pickOnBounds="true" preserveRatio="true">
<image>
<Image url="/com/example/app/resources/icons/instrument.png" />
</image>
</ImageView>
</graphic>
</Button>
但是我得到:
该按钮增加了高度,因此不再与其他没有图像的按钮对齐。
最佳答案
您可以在fxml中执行类似的操作
<Button layoutX="104.0" layoutY="81.0" mnemonicParsing="false" text="Love Potion">
<font>
<Font size="30.0" />
</font>
<graphic>
<ImageView fitHeight="150.0" fitWidth="200.0" pickOnBounds="true" preserveRatio="true">
<image>
<Image url="http://icons.iconarchive.com/icons/mirella-gabriele/fantasy-mediaeval/128/Poison-red-icon.png" />
</image>
</ImageView>
</graphic>
</Button>
在此处查看示例Styling a JavaFX 2 button using FXML only - How to add an image to a button?
更新:
如果您使用Java 8
float width = com.sun.javafx.tk.Toolkit.getToolkit().getFontLoader().computeStringWidth(btn.getText(), btn.getFont());
然后使用
image
的宽度。