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>
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>
Additional Resources
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!