1

I would like to include buttons with icon and text using FXML.

I know that in FXML I can add an image with the following code:

<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.

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:

enter image description here

The button increases its height and therefore is no longer aligned with the other buttons without images.

M.E.
  • 4,955
  • 4
  • 49
  • 128
  • 1
    Possible duplicate of [Styling a JavaFX 2 button using FXML only - How to add an image to a button?](https://stackoverflow.com/questions/16340269/styling-a-javafx-2-button-using-fxml-only-how-to-add-an-image-to-a-button) – PrimosK Jun 13 '19 at 06:18
  • alignment/sizing of children is the task of a layout - choose one that's suitable for your requirements. BTW, you showed what you _don't_ want, better would be to explain what you _do_ want to achieve, best with a [mcve] – kleopatra Jun 14 '19 at 06:55

2 Answers2

2

You could do something like this in 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?

UPDATE: if you use Java 8

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

then use the width for the image.

Raw
  • 461
  • 7
  • 15
  • This works but how could I make the image have the same width as text? -see edit- – M.E. Jun 13 '19 at 10:43
  • beware: don't do any manual sizing/positioning - instead add the buttons into a layout that does it for you. – kleopatra Jun 13 '19 at 10:58
0

You can try with css:

<Button fx:id="myB" text="DATE" mnemonicParsing="false" prefHeight="150.0" prefWidth="150.0" style="-fx-background-image: url('/img/icons/buttonRed.png');" />
mdrg89
  • 61
  • 5
  • Note a background image is not the same thing as a graphic. However, you can use your approach for a graphic as well via `-fx-graphic: url(...)`. – Slaw Jun 13 '19 at 10:29