简体   繁体   English

JavaFX FXML-带图标和文本的按钮

[英]JavaFX FXML - Button with icon and text

I would like to include buttons with icon and text using FXML. 我想使用FXML包含带有图标和文本的按钮。

I know that in FXML I can add an image with the following code: 我知道在FXML中可以使用以下代码添加图像:

<ImageView id="boxImage" fitWidth="100" fitHeight="100">
  <image>
    <Image url="@/com/example/app/resources/icons/office.png" />
  </image>            
</ImageView>

But I am wondering how to merge that with a button code: 但我想知道如何将其与按钮代码合并:

<Button text="DATE"/>

Any help or example is really welcomed as I am totally lost on how to apply an image using FXML. 真的很欢迎任何帮助或示例,因为我完全不知道如何使用FXML应用图像。

Edit 编辑

Following answers I did: 我做了以下回答:

<Button text="INSTRUMENT" styleClass="">
    <graphic>
        <ImageView pickOnBounds="true" preserveRatio="true">
            <image>
                <Image url="/com/example/app/resources/icons/instrument.png" />
            </image>
        </ImageView>
    </graphic>
</Button>

But I get: 但是我得到:

在此处输入图片说明

The button increases its height and therefore is no longer aligned with the other buttons without images. 该按钮的高度增加,因此不再与其他没有图像的按钮对齐。

You could do something like this in fxml 您可以在fxml中执行类似的操作

<Button layoutX="104.0" layoutY="81.0" mnemonicParsing="false" text="Love&#10;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>

See the example here Styling a JavaFX 2 button using FXML only - How to add an image to a button? 请参阅此处的示例, 仅使用FXML对JavaFX 2按钮进行样式设置-如何向按钮添加图像?

UPDATE : if you use Java 8 更新 :如果您使用Java 8

float width = com.sun.javafx.tk.Toolkit.getToolkit().getFontLoader().computeStringWidth(btn.getText(), btn.getFont());

then use the width for the image . 然后使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM