简体   繁体   中英

Filling a combo box with list of available fonts, Java

How would I use the GraphicsEnvironment.getAllFonts() method to populate a combo box with a list of all available fonts?


I used

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

But this didn't work.

Regarding,

I used JComboBox font = new JComboBox(GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts());
That hasn't worked.

It does work. But you have to set the list cell renderer to display the font name. For example,

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));

This is all well described in the combo box tutorial .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM