14

I have a JButton and I want to add an icon to it. I would like to use the font based icons from FontAwesome which provides a TrueType font file. The icon I am trying to add is the play button icon. The play button icon in the css file for FontAwesome is \f04b which I beleive translates to \uf04b in Java.

This is how I am loading the font in the constructor of by IconButton base class.

public class IconButton extends JButton {
  public IconButton() {
    try {
      InputStream in = this.getClass().getResourceAsStream("/fontawesome-webfont.ttf");
      Font ttfBase = Font.createFont(Font.TRUETYPE_FONT, in);
      Font ttfReal = ttfBase.deriveFont(Font.BOLD, 24);
      setFont(ttfReal);
    } catch (FontFormatException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
  }
}

In the implementing class StartButton this is how I am setting the text.

public class StartButton extends IconButton {
  public StartButton() {
    setText(String.valueOf('\u0f4b'));
    setForeground(Color.BLACK);
  }
}

This is what I get. Nothing.

JButton

Any help is much appreciated.

EDIT: See answer below.

merv
  • 67,214
  • 13
  • 180
  • 245
rmontgomery429
  • 14,660
  • 17
  • 61
  • 66
  • That first code wold not compile (`createFont` throws exceptions that are neither caught nor declared), and it seems terrible design of the two classes shown ( 1. the first class could create the Font once and cache it as a static attribute 2. if it defined a constructor based around a String for the text, calling the super constructor, it could avoid the second class completely). Alternately A. since `IconButton` sets a `Font` and `StartButton` sets a foreground color, use a standard `JButton` and hand each one to a method to configure the look. B. Use a new PLAF or adjust the `UIManager` – Andrew Thompson Mar 10 '12 at 03:39
  • The code wasn't pulled verbatim from the application in order to reduce noise, but for completeness sake I've updated it to include the try/catch. I would also add that I agree it should only create the Font once. Good suggestion. I'll have to look into PLAF and the UIManger. – rmontgomery429 Mar 11 '12 at 04:41
  • *"The code wasn't pulled verbatim from the application"* Probably better to describe it in words or pseudo-code (clearly marked as such) rather than Java code in that case. Good call on updating it. :) – Andrew Thompson Mar 11 '12 at 06:05

2 Answers2

12

I think I solved this actually. The correct character is \uf04b not \u0f4b. Whoops! :)

This is working for me now.

JButton with Play Icon

rmontgomery429
  • 14,660
  • 17
  • 61
  • 66
2

Try jIconFont (Swing or JavaFX) at http://jiconfont.github.io/

Example:

Icon icon = IconFontSwing.buildIcon(FontAwesome.FLOPPY_O, 15);

JButton button = new JButton(icon);
Carlos Eduardo
  • 740
  • 6
  • 10