Jesse James
Jesse James

Reputation: 1223

Is it possible to add a Tree inside a JCombobox?

Since I have too many options in my JComboBox, I thought maybe regrouping them based on their type in different nodes and let the user expand or collapse them depending on which type they like would be a good idea. This would improve the readability of the JComboBox and save the user a lot of time scrolling down or up looking for their option.

The question now is, is it possible to add a tree in a JComboBox?

The closest thing to a solution I have found on SO is this one: One Alternative

The person who came up with the alternative is suggesting the following:

If you need expansion of nodes, then a better option would be to add a popup that appears below a button that listens for selections of items in the tree. Something like this might be a better choice depending on how your GUI is laid out.

But, and unless I misunderstood what they are saying, they are not adding the tree inside the JComboBox, which is really what I want here.

Upvotes: 1

Views: 299

Answers (1)

Sergiy Medvynskyy
Sergiy Medvynskyy

Reputation: 11327

Yes you can replace JList in popup component by JTree. But you need also to provide communication between ComboBoxModel and TreeModel (when an item is selected in JTree, it will also selected in JComboBox and vice versa). For example you can build implementation of ComboBoxModel, that has a TreeModel as delegate, and provides linearization of your tree each time when your TreeModel changes (fires a TreeModelEvent), to get the item list for combobox. Also you need to provide reaction for mouse/key events in your tree, to update selection in your combobox.

Here is the method you can use to set any component as popup of a JComboBox (in your case it should be a JScrollPane that wraps your JTree):

/**
 * Sets the custom component as popup component for the combo-box.
 *
 * @param combo combo-box to get new popup component.
 * @param comp new popup component.
 * @param widthIncr width increment for pop-up.
 * @param heightIncr height increment for pop-up.
 */
public static void setPopupComponent(JComboBox<?> combo, Component comp, int widthIncr, int heightIncr) {
    final ComboPopup popup = (ComboPopup) combo.getUI().getAccessibleChild(combo, 0);
    if (popup instanceof Container) {
        final Container c = (Container) popup;
        c.removeAll();
        c.setLayout(new GridLayout(1, 1));
        c.add(comp);
        final Dimension size = comp.getPreferredSize();
        size.width += widthIncr;
        size.height += heightIncr;
        c.setPreferredSize(size);
    }
}

Parameters widthIncr and heightIncr could be used for some Look-and-Feels to better adopt default width/heght of popup in your combobox.

Upvotes: 3

Related Questions