Reputation: 11
I have an application that uses a Swing - JCombobox.
I prepared standard DefaultComboBoxModel and I added all items to model, but I would like hide from users some items when he wants select them from PopupMenu.
I don't want to change the model(remove items).
Upvotes: 1
Views: 3042
Reputation: 1955
Cache your objects in a list and then use it to build your combo...
List objects<ComboItem> = new ArrayList<ComboItem>;
objects.add(1,"Visible String 1", "Value 1");
objects.add(1,"Visible String 2", "Value 2");
objects.add(2,"Visible String 3", "Value 3");
...
class ComboItem
{
private int group;
private String key;
private String value;
public ComboItem(int group, String key, String value)
{
this.group = group;
this.key = key;
this.value = value;
}
@Override
public String toString()
{
return key;
}
public int getGroup()
{
return group;
}
public String getKey()
{
return key;
}
public String getValue()
{
return value;
}
}
...
from here you add item that only from the group you need.. upon user selection.
iterate through you list and add the ones you want according to its group for example.
for (String temp : objects) {
if (temp.getGroup == 1) {
comboBox.add(temp.key.temp.value);
}
}
Upvotes: 0
Reputation: 4847
You could keep the items in a separate master list and dynamically create the filtered Model based on the user action.
Upvotes: 2
Reputation: 408
If I got your question right the following article may be of use - instead of removing the item, you can disable it based on some condition:
Upvotes: 0
Reputation: 657
The best way is to add/remove items in the model.
If you don't want that approach, you can have different models with different items and set them appropriately to the JComboBox.
Upvotes: 0