我想使用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>
但是我得到了
该按钮增加了高度,因此不再与其他没有图像的按钮对齐。
答案 0 :(得分:2)
您可以在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
的宽度。
答案 1 :(得分:0)
您可以尝试使用CSS:
<Button fx:id="myB" text="DATE" mnemonicParsing="false" prefHeight="150.0" prefWidth="150.0" style="-fx-background-image: url('/img/icons/buttonRed.png');" />