Youcef Laidani Youcef Laidani - 1 year ago 67
Java Question

Text not show correct FontAwesome and Swing

I tried to follow this example Font Awesome with Swing

Every thing work fine but when i tried to add some text the font not show correct, it show me something like this:

My code

try (InputStream is = TestFontAwsome.class.getResourceAsStream("fontawesome-webfont.ttf")) {
Font font = Font.createFont(Font.TRUETYPE_FONT, is);
font = font.deriveFont(Font.PLAIN, 24f);

JLabel label = new JLabel("\uf0c0 font not correct");


JFrame frame = new JFrame("Testing");
frame.setLayout(new GridBagLayout());
} catch (IOException | FontFormatException exp) {

The result

Error when set font

I already installed the Font:

Install the font

Any idea about the problem?

Answer Source
JLabel label = new JLabel("\uf0c0 font not correct");

The JLabel font is set to Font Awesome, which has no glyph for the ascii text provided in the JLabel. AFAIK there is not a way to mix the fonts within a single JLabel - you may be able to do this with some form of html, but a easier solution might be to just use two JLabels with different fonts.

JLabel l1 = new JLabel("\uf0c0");
JLabel l2 = new JLabel("This is ascii text");
Box mix = Box.createHorizontalBox();
mix.add(l1); mix.add(l2);

You can alternatively custom paint a Component using paintComponent, setting the Font as needed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download