如何使用GraphicsEnvironment.getAllFonts()方法在组合框中填充所有可用字体的列表?



我用了

JComboBox font = new
    JComboBox(GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts());


但这没有用。

最佳答案

关于,


  我使用了JComboBox font = new JComboBox(GraphicsEnvironment.getLocalGraphicsEnvironment()。getAllFonts());
  那没有用。


确实有效。但是您必须设置列表单元格渲染器以显示字体名称。例如,

GraphicsEnvironment graphEnviron =
       GraphicsEnvironment.getLocalGraphicsEnvironment();
Font[] allFonts = graphEnviron.getAllFonts();

JComboBox<Font> fontBox = new JComboBox<>(allFonts);
fontBox.setRenderer(new DefaultListCellRenderer() {
   @Override
   public Component getListCellRendererComponent(JList<?> list,
         Object value, int index, boolean isSelected, boolean cellHasFocus) {
      if (value != null) {
         Font font = (Font) value;
         value = font.getName();
      }
      return super.getListCellRendererComponent(list, value, index,
            isSelected, cellHasFocus);
   }
});
JOptionPane.showMessageDialog(null, new JScrollPane(fontBox));


combo box tutorial中对此进行了很好的描述。

07-24 20:21