views:

1254

answers:

4

For my application, I want a Combo Box that displays its elements when dropped down as a Tree. Problem is, I'm not versed well enough in Swing to know how to go about doing this. At least without ending up writing a new widget from scratch, or something to that effect.

How would I do something like this without creating one from scratch?

A: 

Override the getListCellRendererComponent methode and create the components in level order. For every tree level move the painted string 3 spaces to right.

Example:

1

. a

. b

2

. c

The original implementation you can look from

public Component getListCellRendererComponent(
                                       JList list,
                                       Object value,
                                       int index,
                                       boolean isSelected,
                                       boolean cellHasFocus) {
        //Get the selected index. (The index param isn't
        //always valid, so just use the value.)
        int selectedIndex = ((Integer)value).intValue();

    if (isSelected) {
        setBackground(list.getSelectionBackground());
        setForeground(list.getSelectionForeground());
    } else {
        setBackground(list.getBackground());
        setForeground(list.getForeground());
    }

    //Set the icon and text.  If icon was null, say so.
    ImageIcon icon = images[selectedIndex];
    String pet = petStrings[selectedIndex];
    setIcon(icon);
    if (icon != null) {
        setText(pet);
        setFont(list.getFont());
    } else {
        setUhOhText(pet + " (no image available)",
                    list.getFont());
    }

    return this;
}
Markus Lausberg
But wouldn't that lose the expand collapse behavior
OscarRyz
A: 
OscarRyz
Yeah that's just what I was thinking, but I'm not sure how it would handle folding/unfolding vs. selecting an element. I'll give it a shot soon.
Daddy Warbox
Don't do it. Looks terrible. :S
OscarRyz
Hmm. Any other suggestions?
Daddy Warbox
This is absolutely useless code. It doesn't do what is required and it do it it worst possible way. (-1)
Rastislav Komara
+2  A: 
OscarRyz
Cool, but I'm not sure I'd be willing to pay for something that I'm only gonna use a tiny bit of. Thanks for the find, though.
Daddy Warbox
Yeap. I agree. Then suggestion of show/hide a panel with the jtree will do. I'm pretty sure that's how they did that implementation.
OscarRyz
+3  A: 

I think I would implement this as a JTree component in a JViewPort, followed by an expansion button. When collapsed, it would look like a combo box. When you click the expansion button, the viewport would expand, allowing you to scroll and select a node in the JTree. When you selected the node, the view port would collapse back to only show the selected node and the expansion button.

Ken Paul
Sounds like a bit of work, but I suppose that'll do. I'll just have to play around with it.
Daddy Warbox