How to change font in Java gui application?
You can 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 is a great way to check font names.
If you do this, you will find that "Comic Sans" is listed as "Comic Sans MS", which means you need to use something like new Font("Comic Sans MS", Font.PLAIN, 24)
to create a new font
For example...
Shown: Comic Sans MS, Calibri, Default and 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);
}
}
source to share
I assume you tried to put comics and caliber in the constructor. If it doesn't work, make sure it's a valid font in your case. through -
String FontList[];
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
FontList = ge.getAvailableFontFamilyNames();
FontList [] contains all available font types
source to share