Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add icons to JButton using custom font from AwesomeFont and unicode characters in Java Swing?

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.

like image 594
rmontgomery429 Avatar asked Mar 09 '12 19:03

rmontgomery429


People also ask

How to add icons to buttons in Java swing?

To add icon to a button, use the Icon class, which will allow you to add an image to the button. Icon icon = new ImageIcon("E:\editicon. PNG"); JButton button7 = new JButton(icon);


2 Answers

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

This is working for me now.

JButton with Play Icon

like image 158
rmontgomery429 Avatar answered Oct 12 '22 06:10

rmontgomery429


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

Example:

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

JButton button = new JButton(icon);
like image 43
Carlos Eduardo Avatar answered Oct 12 '22 04:10

Carlos Eduardo