Java Swing How to - Set text size of JComboBox with DefaultListCellRenderer








Question

We would like to know how to set text size of JComboBox with DefaultListCellRenderer.

Answer

import java.awt.Component;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
//  w w  w  . j a  va  2  s.  c o  m
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;

public class Main {

  public static void main(String[] args) {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    String[] fonts = ge.getAvailableFontFamilyNames();
    JComboBox<String> fontChooser = new JComboBox<>(fonts);
    fontChooser.setRenderer(new FontCellRenderer());
    JOptionPane.showMessageDialog(null, fontChooser);

  }
}

class FontCellRenderer extends DefaultListCellRenderer {
  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((String) value, Font.PLAIN, 20);
    label.setFont(font);
    return label;
  }
}