package bjc.utils.gui; import java.awt.Component; import java.util.function.Function; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; /** * Simple implementation of {@link ListCellRenderer} that uses a custom label. * * This renderer does the simple task of using a custom 'toString' method to display text for a given data type. * * @param The data-type being displayed */ public class DelegateListCellRenderer extends JLabel implements ListCellRenderer { private static final long serialVersionUID = -3312631037740011026L; private Function toStringer; /** * Create a new renderer using a given toString function * * @param toStringer The toString function to use */ public DelegateListCellRenderer(Function toStringer) { super(); this.toStringer = toStringer; } @Override public Component getListCellRendererComponent(JList list, E value, int index, boolean isSelected, boolean cellHasFocus) { String val = toStringer.apply(value); setText(val); if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } setEnabled(list.isEnabled()); setFont(list.getFont()); setOpaque(true); return this; } }