You are currently browsing the Philipp Meier's weblog posts tagged: nimbus


news
research

Don’t subclass DefautListCellRenderer for Swing’s Nimbus LAF

If you follow the common practice to subclass JLabel to add some formatting to your combobox you will be surprised that this will break the rendering of JComboBoxes in the Nimbus Look Ant Feel.

Examples of bad JLabel-based CellRenderer

Basically the nice glass like look of the combobox will disappear and the old flat look will be restored. This comes due to Nimbus using a custom CellRenderer:

javax.swing.plaf.synth.SynthComboBoxUI$SynthComboBoxRenderer

Fortunately this renderer is based on JLabel, too. This is why you can simply wrap the renderer and add some blinkenlights when needed:

Good example of renderer wrapping the original renderer

The implementation is straight forward:

[source:java]
public class InstanceWithIconCellRendererWrapper implements ListCellRenderer {
private final ListCellRenderer wrapped;
public InstanceWithIconCellRendererWrapper(ListCellRenderer listCellRenderer) {
this.wrapped = listCellRenderer;
}
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
String displayName = String.valueOf(value); // customize here
Component renderer = wrapped.getListCellRendererComponent(list, displayName, index, isSelected, cellHasFocus);
if (renderer instanceof JLabel) {
Icon icon = new ImageIcon(); // customize here
((JLabel) renderer).setIcon(icon);
}
return renderer;
}
}
[/source]

Use it as follows:


jComboBox.setRenderer(new InstanceWithIconCellRendererWrapper(jComboBox.getRenderer()));

tour
tools
Bear