I wanted to change the font in my Java GUI application.
Currently I am using Font newFont = new Font("Serif", Font.BOLD, 24);. To change the font.
How can I use fonts like 'comic sans' or 'calibri' in my GUI based application in Java ?
Currently I am using jdk 1.60.
You could start by listing the available font names using something like...
String fonts[]
= GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
for (int i = 0; i < fonts.length; i++) {
System.out.println(fonts[i]);
}
This a great little way of checking the font names.
If you did this, you would find that "Comic Sans" is listed as "Comic Sans MS", this means you'll need to use something like new Font("Comic Sans MS", Font.PLAIN, 24) to create a new font
For example...

Showing: Comic Sans MS, Calibri, Look and feel default
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JLabel label = new JLabel("Hello");
label.setFont(new Font("Comic Sans MS", Font.PLAIN, 24));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(label, gbc);
label = new JLabel("Hello");
label.setFont(new Font("Calibri", Font.PLAIN, 24));
add(label, gbc);
label = new JLabel("Hello");
Font font = label.getFont();
label.setFont(font.deriveFont(Font.PLAIN, 24f));
add(label, gbc);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
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