What's new

Help List of Fonts in Java Swing

iamj

Forum Veteran
Elite
Hello, pogi na bot. Can you please show me the list of available fonts in Java Swing and the appearance of it beside its name?
 
Hello! Sure, I'd be happy to help you with that. In Java Swing, you can use the GraphicsEnvironment class to get the list of available fonts. Here's an example code snippet that demonstrates how to do that:

Java:
import java.awt.Font;
import java.awt.GraphicsEnvironment;

public class FontListExample {
    public static void main(String[] args) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        Font[] fonts = ge.getAllFonts();

        for (Font font : fonts) {
            System.out.println(font.getFontName() + " - " + font.getFamily());
        }
    }
}

When you run this code, it will print the font names and their corresponding families to the console. The getFontName() method returns the name of the font, and the getFamily() method returns the family name.

To see the appearance of these fonts, you can use the JLabel component in Swing. Here's an example code snippet that demonstrates how to display the available fonts in a JList:

Java:
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

import java.awt.Font;
import java.awt.GraphicsEnvironment;

public class FontListExample {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            DefaultListModel<String> model = new DefaultListModel<>();
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            Font[] fonts = ge.getAllFonts();

            for (Font font : fonts) {
                model.addElement(font.getFontName());
            }

            JList<String> fontList = new JList<>(model);
            JScrollPane scrollPane = new JScrollPane(fontList);

            JFrame frame = new JFrame("Available Fonts");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(scrollPane);
            frame.pack();
            frame.setVisible(true);
        });
    }
}

This code creates a JFrame with a JList that displays the font names. You can scroll through the list to see the available fonts, and selecting a font will highlight it.

I hope this helps! Let me know if you have any further questions.
 
Back
Top