查看 Font.canDisplay(...) 方法以帮助您确定是否可以使用您的字体。
为此,我使用了 JTextArea。
这是一个简单的演示,列出了您机器上可用的字体:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
public class ComboBoxFonts extends JFrame implements ItemListener
{
JTextArea textArea;
JComboBox comboBox;
public ComboBoxFonts()
{
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment ();
Font [] fonts = ge.getAllFonts ();
comboBox = new JComboBox( fonts );
comboBox.setRenderer( new MyFontRenderer() );
comboBox.addItemListener( this );
getContentPane().add( comboBox, BorderLayout.SOUTH );
textArea= new JTextArea("Some text", 3, 20);
getContentPane().add( new JScrollPane( textArea ) );
}
public void itemStateChanged(ItemEvent e)
{
Font font = (Font)e.getItem();
textArea.setFont( font.deriveFont( textArea.getFont().getSize2D() ) );
comboBox.setFont( font.deriveFont( comboBox.getFont().getSize2D() ) );
}
public static void main(String[] args)
{
ComboBoxFonts frame = new ComboBoxFonts();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
class MyFontRenderer extends BasicComboBoxRenderer
{
public Component getListCellRendererComponent(
JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
Font font = (Font)value;
setFont( font.deriveFont(12.0f) );
setText( font.getName() );
return this;
}
}
}