I\'m trying to use a special font in my JFrame, but I\'m running into problems. I have a JLabel defined like this:
private JLabel lab = new JLabel(\"Text\");
The Font you created has to be registered first in the GraphicsEnvironment
to be accessible to all and derive the size of the font:
Font font = Font.createFont(Font.TRUETYPE_FONT, getClass().getResource("/CUSTOMFONT-MEDIUM.TTF").openStream());
GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
genv.registerFont(font);
// makesure to derive the size
font = font.deriveFont(12f);
@sasankad is mostly correct (+1).
Once you have created the font, it will have a default size of 1
Font font = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/CUSTOMFONT-MEDIUM.TTF"));
You then need to derive the font size and style you want.
Font biggerFont = font.deriveFont(Font.BOLD, 48f);
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestCustomFont {
public static void main(String[] args) {
new TestCustomFont();
}
public TestCustomFont() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
try {
Font font = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/Royal Chicken.ttf"));
JLabel happy = new JLabel("Happy little Miss Chicken");
happy.setFont(font.deriveFont(Font.BOLD, 48f));
add(happy);
} catch (FontFormatException | IOException ex) {
ex.printStackTrace();
}
}
}
}
Check out java.awt.Font for more details...
You may also want to take a look at Physical and Logical Fonts, Font Configuration Files