How to use font awesome in a fxml project (javafx)

后端 未结 6 450
深忆病人
深忆病人 2020-11-29 11:02

I want to use font font awesome in my project but I have no idea how to use font awesome in my project.

I had found some example but they can\'t be use in fxml.

6条回答
  •  醉梦人生
    2020-11-29 11:46

    I achieved using FA Icons by adapting Jens Deters's approach.

    His routines target dynamic gui composition opposing fxml's declarative way. Nevertheless, his AwesomeIcon enumeration (which maps FA comprehensible names with unicode characters) suited perfectly to my intents.

    It should start by statically load the font in main/app class:

    public class App extends Application {
        static {
            Font.loadFont(App.class.getResource("/font/fontawesome-webfont.ttf").toExternalForm(), 10);
        }
    
        @Override
        public void start(final Stage primaryStage) throws Exception {
            URL resource = getClass().getResource("/fxml/app.fxml");
            primaryStage.setScene(new Scene((Parent) FXMLLoader.load(resource), 500, 500));
            primaryStage.setTitle("FontAwesomeFX demo");
            primaryStage.show();
        }
    
        public static void main(String... args){
            launch(args);
        }
    }
    

    One can not use unicode characters in fxml (as needed to specify FA Icons), but can dynamic set attributes with such values. Hence having the above mentioned enumeration (AwesomeIcon), the job was done:

    1. The import:

      
      
    2. The node:

      
      

    I end up implementing an Icon Widget/Control/Component for resuming the amount of code with two properties:

    1. value: FA Icon Name;
    2. size: styleable attribute for style -fx-font-size on label.

    New code (same effect):

    
    

    The code for that control can be found here. You can also find an working example as it includes the font and testing code.

提交回复
热议问题