Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Feb 24, 2000

Customizing a JComboBox

The JComboBox API provides a programmer with very little direct control over how list items are displayed. This is because, in true object-oriented fashion, a JComboBox object knows or cares very little about the items it displays to the user. It only knows that it displays Components, which it gets from its ListCellRenderer's getListCellRendererComponent() method.

Unless a JComboBox is using a custom renderer, it will be using an instance of the javax.swing.plaf.basic.BasicComboBoxRenderer, which is a subclass of JLabel. Armed with this knowledge, a programmer can easily modify the appearance of the list items through methods provided by the JLabel class. Try these lines of code on a JComboBox object 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 custom class which implements the javax.swing.ListCellRenderer interface and passing an instance of it to JComboBox's setRenderer() method.
David Glasser
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap