Reputation: 23
I would like to obtain String representation of all the items contained in the JComboBox's model, how to do this?
ListModel model = combobox.getModel();
for(int i = 0; i < model.getSize(); i++)
{
componentTexts.add( model.getElementAt( i ).toString() );
}
This gives me different strings than combobox items - CellRenderer decides about the every combobox item's label text?
Upvotes: 1
Views: 209
Reputation: 324098
If your rendered text is different than the toString() of the Object then you need to invoke the renderer directly.
The code might be something like:
ListCellRenderer renderer = comboBox.getRenderer();
Object child = comboBox.getAccessibleContext().getAccessibleChild(0);
BasicComboPopup popup = (BasicComboPopup)child;
JList list = popup.getList();
ListModel model = combobox.getModel();
for(int i = 0; i < model.getSize(); i++)
{
Object value = model.getElementAt(i);
JLabel label = (JLabel)renderer.getListCellRendererComponent(list, value, i, false, false);
components.add( label.getText() );
}
Upvotes: 2
Reputation: 5486
Basically, you can't in every case, because the CellRenderer does not return a String, but could return any JComponent it feels is appropriate to show, e.g. also an icon, an image, a color patch, or something more complex.
Still, you could try to access the combobox' CellRenderer and ask the cellRenderer for each Combobox item. This will return you a JComponent. If it is a JLabel (which it probably often is), you use the getText() method to extract the text. Something like:
if (component instance JLabel) {
componentTexts.add ((JLabel) component).getText());
}
Upvotes: 0