How to change font in Java gui application?

I wanted to change the font in my Java GUI application.

I am currently 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 Java GUI based application?

I am currently using jdk 1.60.

+2


source to share


2 answers


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

Font

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

}

      

+8


source


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

+1


source







All Articles