[英]JavaFX FXML - Button with icon and text
我想使用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>
請參閱此處的示例, 僅使用FXML對JavaFX 2按鈕進行樣式設置-如何向按鈕添加圖像?
更新 :如果您使用Java 8
float width = com.sun.javafx.tk.Toolkit.getToolkit().getFontLoader().computeStringWidth(btn.getText(), btn.getFont());
然后使用image
的寬度。
您可以嘗試使用CSS:
<Button fx:id="myB" text="DATE" mnemonicParsing="false" prefHeight="150.0" prefWidth="150.0" style="-fx-background-image: url('/img/icons/buttonRed.png');" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.