简体   繁体   中英

Colored Icon Font in JavaFX

I have a JavaFX application in which I would like to use a few icons. Currently, I parse all text that might have an icon in it for a specific string a characters, for example ":icon:", and I build TextFlow in which I replace the matched keywords with an image. Then I just display the TextFlow as a graphic within the Label/TextField/etc. This feels very sloppy to me. Is there a better solution?

I would like to use a custom font which replaces a few unicode characters with the small number of icons I want to use, but it is essential that the icons have color in them. Is this something that can be done with a font? Can I use CSS to color specific characters of text? Am I on the right path here at all?

You may wish to use a web font for this.

This sample uses the Google Material design icons font .

爱你

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;

public class MixedTextAndIconFonts extends Application {
    @Override public void start(Stage stage) {
        Text i = new Text("I");
        Text love = new Text("\uE87D");
        Text u = new Text("you");
        i.setStyle("-fx-font-family: \'Indie Flower\'; -fx-font-size: 80; -fx-fill: forestgreen;");
        love.setStyle("-fx-font-family: \'Material Icons\'; -fx-font-size: 60; -fx-fill: firebrick;");
        u.setStyle("-fx-font-family: \'Indie Flower\'; -fx-font-size: 80; -fx-fill: forestgreen;");

        TextFlow textFlow = new TextFlow(
                i,
                love,
                u
        );
        textFlow.setStyle("-fx-padding: 20px; -fx-background-color: azure;");

        Scene scene = new Scene(textFlow);
        scene.getStylesheets().add("http://fonts.googleapis.com/css?family=Indie+Flower");
        scene.getStylesheets().add("http://fonts.googleapis.com/css?family=Material+Icons");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) { launch(args); }
}

For a quick sample, I inline the styles, but for a "real" app, you would probably use an external CSS stylesheet and meaningful constant names for the unicode code points of the icon glyphs you wish to include.

Further resources

There are other similar resources available on the web if you search for them, such as fontawesomefx , icon8 webfont conversion guide and icomoon.io .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM