Now, I know, different font families can be achieved within a JButton text. Like below
JButton button = new JButton("<html><font face=Arial>Hello </font><font face=Verdana>World</font></html>");
It looks like this. "Hello" with Arial and "World" with Verdana.
enter image description here
But, what if I want a word to have a font which I've created using Font.createFont() method. I thought, something like this, would have worked.
Font myFont = createMyFont();
JButton button = new JButton("<html><font face=MyFont>Hello </font>World</html>");
The significance of this question is that I am creating a multilingual software, which has two fonts in a single JButton.
So, I want my JButton to be like this:
enter image description here
But, it is like this:
enter image description here
1 Answer 1
Register custom font with:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment()
ge.registerFont(myFont);
After, provide file name, something like:
URL fontUrl;
try {
fontUrl = new URL("http://www.webpagepublicity.com/" +
"free-fonts/a/Airacobra%20Condensed.ttf"); // dummy font
Font myFont = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream());
myFont = myFont.deriveFont(Font.PLAIN,20);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(myFont);
button.setText("<html><font face='Airacobra Condensed'>Hello </font>World</html>");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (FontFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The filename can be accquired on windows by rightclicking on the font file, selecting Properties -> Details and there it's the title. Example: FontAwesome Regular.
enter image description here
Font.registerFont()after creating the font usingFont.createFont()GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); ge.registerFont(myFont);