【问题标题】:JavaFX FXML - Button with icon and textJavaFX FXML - 带有图标和文本的按钮
【发布时间】:2019-10-27 15:47:12
【问题描述】:

我想使用 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>

但我明白了:

按钮增加了它的高度,因此不再与其他没有图像的按钮对齐。

【问题讨论】:

标签: java javafx fxml


【解决方案1】:

你可以在 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>

在此处查看示例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 的宽度。

【讨论】:

  • 这可行,但我怎样才能使图像与文本具有相同的宽度? -见编辑-
  • 当心:不要进行任何手动调整大小/定位 - 而是将按钮添加到适合您的布局中。
【解决方案2】:

你可以试试css:

<Button fx:id="myB" text="DATE" mnemonicParsing="false" prefHeight="150.0" prefWidth="150.0" style="-fx-background-image: url('/img/icons/buttonRed.png');" />

【讨论】:

  • 请注意,背景图像与图形不同。但是,您也可以通过-fx-graphic: url(...) 将您的方法用于图形。
猜你喜欢
  • 2016-09-03
  • 2015-01-12
  • 2014-05-22
  • 1970-01-01
  • 1970-01-01
  • 2020-08-30
  • 2018-09-01
  • 1970-01-01
  • 2015-07-21
相关资源
最近更新 更多