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.
Any help is much appreciated.
EDIT: See answer below.
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);
I think I solved this actually. The correct character is \uf04b
not \u0f4b
. Whoops! :)
This is working for me now.
Try jIconFont (Swing or JavaFX) at http://jiconfont.github.io/
Example:
Icon icon = IconFontSwing.buildIcon(FontAwesome.FLOPPY_O, 15);
JButton button = new JButton(icon);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With