Customizing a JComboBox

The JComboBox API provides a programmer with very little directcontrol over how list items are displayed. This is because, in trueobject-oriented fashion, a JComboBox object knows or cares very littleabout the items it displays to the user. It only knows that itdisplays Components, which it gets from its ListCellRenderer’sgetListCellRendererComponent() method.

Unless a JComboBox is using a custom renderer, it will be using aninstance of the javax.swing.plaf.basic.BasicComboBoxRenderer, which isa subclass of JLabel. Armed with this knowledge, a programmer caneasily modify the appearance of the list items through methodsprovided by the JLabel class. Try these lines of code on a JComboBoxobject named comboBox:

 ListCellRenderer r = comboBox.getRenderer();((JLabel) r).setHorizontalAlignment(SwingConstants.CENTER);((JLabel) r).setBorder(new BevelBorder(BevelBorder.LOWERED));((JLabel)r).setIcon(javax.swing.plaf.metal.MetalIconFactory.getFileChooserNewFolderIcon());

Even more interesting results can be obtained by writing a customclass which implements the javax.swing.ListCellRenderer interface andpassing an instance of it to JComboBox’s setRenderer() method.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: