How to render image buttons in java fxml using scene builder?

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

So this is my code. I want the image to become a 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>

      

Thank you in advance:)

+3


source to share


3 answers


In your fxml file, import the image batch:

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

      

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



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

      

Then just add the following to the 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>

      

+10


source


The above answer is partially correct by not specifying the "@" and "$" characters in the url and in the "ImageView", for example

<Image fx:id="playbutImg" url="@image/image.png">
<ImageView image="$playbutImg" >

      



Symbol

@ is used to distinguish between a string and a relative directory, if we go through without the @ symbol it will be interpreted as a string and not a relative directory.

+2


source


    <fx:define>
            <Image fx:id="NewTracker" url="@resources/NewTracker.bmp"/>
        </fx:define>
        <Button layoutX="100.0" layoutY="100.0" mnemonicParsing="false" text="New Tracker" >
                <graphic>
                   <ImageView image="$NewTracker"/>
                </graphic>
        </Button>

      

0


source







All Articles