Selected item of the JComboBox not to be listed with all other items
Hi,
I want the selected item of the JComboBox not to be listed with all the other unselected items. But, the selected item item should be displayed. Please help me. Earliest reply is appreciated.
Thanks
[221 byte] By [
subbu1a] at [2007-11-27 11:42:06]

# 1
You are in luck
import java.awt.*;
import javax.swing.*;
public class MyComboBoxTest extends JPanel {
public MyComboBoxTest() {
JComboBox box = new JComboBox();
box.setRenderer( new ComboRenderer( box ) );
for(int i = 0; i < 5; i++) {
box.addItem( "Item " + i );
}
add( box );
}
public class ComboRenderer extends DefaultListCellRenderer {
JComboBox combo;
public ComboRenderer(JComboBox combo) {
super();
this.combo = combo;
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
Component comp = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(value.equals(combo.getSelectedItem()) && index != -1) {
return new JSeparator();
}
return comp;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add( new MyComboBoxTest() );
frame.pack();
frame.setLocation(200,200);
frame.setVisible(true);
}
}
ICE
# 3
I'm not exactly sure, you will still need to display some component there since you cannot return a null value, this might cause an exception, and that cell must also be rendered.
What you can do is to create simple component, much like a JSeparator that would be invisible or have the same color as the background.
This works fine
if(value.equals(combo.getSelectedItem()) && index != -1) {
return Box.createVerticalStrut(1);
}
ICE