Showing the JComboBox selected item text only without the Icon?
I have a JComboBox
that its renderer is a JLabel
with an Icon
for each item in the combo list :
class ComboBoxRenderer extends JLabel implements ListCellRenderer {
public Component getListCellRendererComponent(
JList list,
Object comboItemObject,
int comboItemIndex,
boolean isSelected,
boolean cellHasFocus) {
String comboItemTitle = (String)comboItemObject;
setText( comboItemTitle );
setIcon( ne开发者_开发技巧w ImageIcon( getClass().getResource( "/images/myIcon.png" ) ) );
return this;
}
}
When i select an item from the comboBox i just want to show the selected item text in the comboBox, and not the item icon also. Is there a way i can do that ?
In the rendering code you can check the index. Something like:
if (index == -1)
{
setText(...);
}
else
{
setText(...);
setIcon(...);
}
Also, you should not be reading the image in the rendering code since code is called frequently.
then you have to override isSelected
, and extends JLabel
is useless, because renderer by defalult returns JLabel
as Component
To get the text in the combobox;
a one liner code is all you need.
Create a variable, as I have called mine Combotext
then get the SelectedItem
from the JComboBox
.
ComboText = jComboBox.getSelectedItem();
精彩评论