如何在 Java 中显示 JComboBox 内的不同字体项?
JComboBox 是 JComponent 类的子类,它是由一个文本字段 和一个用户可以选择值的下拉列表组成的。当用户对组合框执行操作时,JComboBox 可以生成ActionListener、ChangeListener 和 ItemListener 接口。我们可以通过实现ListCellRenderer 接口在 JComboBox 中显示不同的字体样式
示例
import java.awt.*; import javax.swing.*; public class JComboBoxFontTest extends JFrame { private JComboBox fontComboBox; private String fontName[]; private Integer array[]; public JComboBoxFontTest() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); fontName = ge.getAvailableFontFamilyNames(); array = new Integer[fontName.length]; for(int i=1;i<=fontName.length;i++) { array[i-1] = i; } fontComboBox = new JComboBox(array); ComboBoxRenderar renderar = new ComboBoxRenderar(); fontComboBox.setRenderer(renderar); setLayout(new FlowLayout()); add(fontComboBox); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } private class ComboBoxRenderar extends JLabel implements ListCellRenderer { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { int offset = ((Integer)value).intValue() - 1; String name = fontName[offset]; setText(name); setFont(new Font(name,Font.PLAIN,20)); return this; } } public static void main(String args[]) { new JComboBoxFontTest(); } }
输出
广告