Search code examples
netbeansjavafxfxmlscenebuilder

how to make image buttons on java fxml using scene builder?


I am using netbeans and want to use media file from my desktop to replace the boring button.

So this is my code. I want it so the image becomes the button.

<Button layoutX="252.0" layoutY="177.0" mnemonicParsing="false" prefHeight="57.0" prefWidth="135.0" text="Button!" textFill="BLUE">
     <font>
        <Font name="Avenir Next Regular" size="13.0" />
     </font>
  </Button>

Thanks in advance :)


Solution

  • In your fxml file, import the image package:

    <?import javafx.scene.image.*?>
    

    then just before the button, assuming image.png is located under "images/" directory and "images/" is located in the same directory as .fxml:

    <fx:define>
       <Image fx:id="btnImage" url="images/image.png" />
    </fx:define>
    

    Then just add the following to your button definition

    <Button layoutX="252.0" layoutY="177.0" mnemonicParsing="false" prefHeight="57.0" prefWidth="135.0" text="Button!" textFill="BLUE">
         <font>
            <Font name="Avenir Next Regular" size="13.0" />
         </font>
    
         <graphic>
            <ImageView image="$btnImage" />
         </graphic>
      </Button>