devxlogo

Customizing a JComboBox

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.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist