Youcef Laidani Youcef Laidani - 23 days ago 9
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");
label.setFont(font);
label.setForeground(Color.red);

label.setFont(font);

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(label);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException | FontFormatException exp) {
exp.printStackTrace();
}
....


The result

Error when set font

I already installed the Font:

Install the font

Any idea about the problem?

Answer
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");
l1.setFont(fontAwesome);
Box mix = Box.createHorizontalBox();
mix.add(l1); mix.add(l2);
myContainer.add(mix);

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

Comments