Search code examples
javajavafxfont-awesomescenebuilderfontawesomefx

How to add a FontAwesomeIcon to a Java File


Hey I want to add a FontAwesomeIcon to a plain Java File - using fontawesomefx.

I generated it with the SceneBuilder and I want to use the graphic that includes FontAwesomeIcon to my Button.

This is the code that SceneBuilder generated:

<Button mnemonicParsing="false" prefHeight="100.0" prefWidth="600.0" style="-fx-background-color: #c93636; -fx-background-radius: 45px; -fx-text-fill: #fff;" text="Zurücksetzen" textAlignment="CENTER">
   <font>
      <Font size="36.0" />
   </font>
   <HBox.margin>
      <Insets left="50.0" />
   </HBox.margin>
   <graphic>
      <FontAwesomeIcon fill="WHITE" glyphName="UNDO" />
   </graphic></Button>

I have everything setup in the Java file - the button works and look like it should the only problem is that I don't know how to load the FontAwesomeFXIcon in the Java file.

This is the part where the Button gets created:

    btnNext.setPrefSize(RESOLUTION.getWidth() / 2, RESOLUTION.getHeight() / 10);                
    btnNext.setStyle("-fx-background-color: #30b832; -fx-background-radius: 90px; -fx-text-fill: #fff; -fx-font-size: 4em;");
    btnNext.setTextAlignment(TextAlignment.CENTER);

It looks like this: enter image description here

But I want it to look like this: enter image description here

Now I tried some things but it did not work.. I guess I have to set the graphic field like its created in the FXML file and then assign a FontAwesomeIcon but I really don't understand how to do this.

I've seen some similar questions but they only want to know on how to use it in FXML which I already do.

I need to have this in the .java file. Without accessing the FXML File and the Controller because I will not use it like this.


Solution

  • So I actually found a Solution myself and it is pretty straight forward.

    First I create a new FontAwesomeIcon Object:

    FontAwesomeIcon fntIcon = new FontAwesomeIcon();
    

    then I assign the GylphName like this:

    fntIcon.setGlyphName("UNDO");
    

    after that I can assign it to my Button and it works! :

    btnReset.setGraphic(fntIcon);
    

    Honestly that was very simple and straight forward !

    ~Faded