3

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.

Siddharth
  • 79
  • 1
  • 1
  • 5

2 Answers2

13

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...

Font

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);
    }

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

I'm assuming you've tried putting comic sans and calibri in the constructor. If it didn't work make sure it is a valid font in your case. check with-

String FontList[]; GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); FontList = ge.getAvailableFontFamilyNames();

FontList[] contains all the font types available

user3744406
  • 45
  • 1
  • 13