Maniek
Maniek

Reputation: 11

How to hide items in JCombobox

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

Answers (5)

Pat B
Pat B

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

RAJKUMAR NAGARETHINAM
RAJKUMAR NAGARETHINAM

Reputation: 1518

You may Create custom combobox model.

Upvotes: 0

basiljames
basiljames

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

Phantomazi
Phantomazi

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:

article

Upvotes: 0

Vito Royeca
Vito Royeca

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

Related Questions