-1

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?

Community
  • 1
  • 1
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140

1 Answers1

1
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.

copeg
  • 8,290
  • 19
  • 28
  • Thank you @copeg, this is about the JLabel and what about the JButton?, i can't do two labels right? – Youcef LAIDANI Nov 11 '16 at 19:37
  • `and what about the JButton` You might try playing around with custom painting by overidding `paintComponent` and setting the Font as needed. – copeg Nov 11 '16 at 19:49
  • 1
    Tow other strategies for buttons. 1) Buttons support HTML as well (but don't look right when the button is disabled, given the text does not change color) 2) Turn the FontAwesome glyph into an image on the fly, and use the image as an icon for the button. Here is a (slightly complicated) example of [turning glyphs into images](http://stackoverflow.com/a/18686753/418556). – Andrew Thompson Nov 12 '16 at 04:52
  • Thank you @AndrewThompson for your answer :) – Youcef LAIDANI Nov 13 '16 at 10:28
  • Technically, it wasn't an answer, just a comment. But you're welcome. :) – Andrew Thompson Nov 13 '16 at 11:14