Home > Java > javaTutorial > body text

How can I programmatically list and preview available fonts in a Java application?

DDD
Release: 2024-10-31 11:12:01
Original
987 people have browsed it

How can I programmatically list and preview available fonts in a Java application?

Getting Information About Fonts

In Java, you can access system fonts through the GraphicsEnvironment class. To obtain an array of all available font family names, use the following code:

<code class="java">GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fonts = ge.getAvailableFontFamilyNames();</code>
Copy after login

Font sizes and styles can be set dynamically during runtime. Consider the following example, which displays a font chooser with a preview of each font:

<code class="java">import java.awt.*;
import javax.swing.*;

public class ShowFonts {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            String[] fonts = ge.getAvailableFontFamilyNames();
            JComboBox fontChooser = new JComboBox(fonts);
            fontChooser.setRenderer(new FontCellRenderer());
            JOptionPane.showMessageDialog(null, fontChooser);
        });
    }
}

class FontCellRenderer extends DefaultListCellRenderer {

    @Override
    public Component getListCellRendererComponent(
            JList list,
            Object value,
            int index,
            boolean isSelected,
            boolean cellHasFocus) {
        JLabel label = (JLabel) super.getListCellRendererComponent(
                list, value, index, isSelected, cellHasFocus);
        Font font = new Font(value.toString(), Font.PLAIN, 20);
        label.setFont(font);
        return label;
    }
}</code>
Copy after login

Additional Resources

  • GraphicsEnvironment.getAvailableFontFamilyNames(): https://docs.oracle.com/javase/7/docs/api/java/awt/GraphicsEnvironment.html#getAvailableFontFamilyNames()
  • DefaultListCellRenderer: https://docs.oracle.com/javase/8/docs/api/javax/swing/DefaultListCellRenderer.html
  • Font Chooser: https://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#font_fonts

The above is the detailed content of How can I programmatically list and preview available fonts in a Java application?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!