how to load Tree inside JComboBox?

早过忘川 提交于 2021-02-19 05:23:25

问题


How can I show a tree inside a JComboBox popup?

Here is example tree:

Theoretical computer science 
           Mathematical logic 
            Automata theory 
Algorithms and data structures
           Analysis of algorithms
           Algorithms

回答1:


There is no default way to put a tree in a combo box. There are a couple of options:

If you can give allowing expansion of nodes, you can achieve a similar effect by adding space before some of the options in a standard JComobBox. Or even space and a dash in front of leaf options.

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.




回答2:


When swinglabs was active there used to be JXComboBox that allows you to have other components in the dropdown like a JTable/JTree. Check here or here you may find the source for it or the documentation.




回答3:


You coud write your own renderer and put a treenode picture in front of the returning label for the subnodes.

Something like:

private static class NodeComboBoxRenderer implements ListCellRenderer {

    protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();

    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        if(value.isSubNode()) { //something to find out
            renderer.setIcon("here comes the resource");
        }
        return renderer;
    }
}



回答4:


I use the TreeComboBox of mindgame (link). It just requires the class AbstractComboBoxUI of the same project.



来源:https://stackoverflow.com/questions/5314207/how-to-load-tree-inside-jcombobox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!