Styling a JavaFX 2 button using FXML only – How to add an image to a button?

Solution using only fxml

As tarrsalah points out, css is the recommended way of doing this, though you can also do it in fxml if you prefer:

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<?import javafx.scene.text.*?>

<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml">
  <children>
    <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>
  </children>
</AnchorPane>

To get the above in SceneBuilder, drag an ImageView on top of a Button and it will automatically be set as a graphic for the button. Then select the ImageView and type the url of the image into the ImageView’s image field in the SceneBuilder properties pane.

Open the above fxml in SceneBuilder to see the image below.

lovepotion


Alternate css attributes

Alternate css to the -fx-background* attributes.

  • -fx-graphic
  • -fx-padding
  • -fx-content-display
  • -fx-graphic-text-gap

These are just different, not necessarily better for what you are trying to do. It is just a preference thing as to which to use. I find these settings easier to use than the -fx-background* settings. They are more restrictive, but the syntax and options are much easier for me to understand and their meanings map to the JavaDoc API for Labeled.

A detailed description of the attributes is in the css reference guide.

Here’s a example with a style setting the graphic embedded in the fxml, though it is always better to separate the style information out into a separate css stylesheet as in tarrsalah’s sample.

<Button layoutX="138.0" layoutY="226.0" mnemonicParsing="false" style="-fx-graphic: url('http://icons.iconarchive.com/icons/mirella-gabriele/fantasy-mediaeval/128/Poison-red-icon.png')" text="Love&#10;Potion">
  <font>
    <Font size="20.0" />
  </font>
</Button>

Related solutions for adding images to buttons using only Java code

  • JavaFX – create custom button with image
  • Add image to a button at a specific position JavaFX

Leave a Comment

tech