【问题标题】:How to make a combobox, inside a jtree, show its menu?如何在 jtree 中制作组合框,显示其菜单?
【发布时间】:2012-08-15 05:38:40
【问题描述】:

我基本上有一个 JTree,我可以在其中显示某些信息。在其中一个“子树”中,我得到了一个面板,该面板由一个带有 GridLayout(0,2) 的面板和一个 JPanel 以及一个组合框组成。

我注意到我的树中没有任何组件对输入做出反应。这当然意味着我的组合框在我尝试单击它时不会做出反应。我试图实现一个默认的单元格编辑器,它可以工作但不像我想要的那样。它基本上打开了菜单,但是当我选择其中一个项目时,它取代了 JLabel,因此只有组合框可见。

图片

点击框之前

点击框后

我尝试过的代码

 TreeCellEditor editor = new DefaultCellEditor(blockedAlternatives);
                infoTree.setEditable(true);
                infoTree.setCellEditor(editor);

我显然不想能够编辑整个树,我只想能够显示组合框的菜单。我只是从网上获取这段代码进行测试。 有什么想法吗?

【问题讨论】:

    标签: java swing jcombobox jtree


    【解决方案1】:

    它基本上打开了菜单,但是当我选择其中一项时 替换了 JLabel,因此只有组合框可见。

    这就是您所期望的,因为这就是 DefaultCellEditor(JComboBox jcb) 的本意:

        import java.awt.BorderLayout;
        import java.util.Properties;
        import javax.swing.*;
        import javax.swing.tree.TreeCellEditor;
    
        public class TreeEditJComboBox {
    
            public static void main(String args[]) {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                Properties props = System.getProperties();
                JTree tree = new JTree(props);
    
    
                JComboBox comboBox = new JComboBox(new String[]{"A", "B", "C"});
                TreeCellEditor editor = new DefaultCellEditor(comboBox);
    
                tree.setEditable(true);
                tree.setCellEditor(editor);
    
                JScrollPane scrollPane = new JScrollPane(tree);
                frame.add(scrollPane, BorderLayout.CENTER);
                frame.setSize(300, 150);
                frame.setVisible(true);
            }
    
        }
    }
    

    您可以尝试创建自己的DefaultCellEditor 并覆盖getTableCellEditorComponent(),然后返回包含JLabelJComboBoxJPanel,类似于:

    class MyDefaultCellEditor extends DefaultCellEditor {
    
    public MyDefaultCellEditor(JComboBox comboBox) {
        super(comboBox);
    }
    
    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
       //return custom coponent
        return super.getTableCellEditorComponent(table, value, isSelected, row, column);
    }
    }
    

    然后:

     TreeCellEditor editor = new MyDefaultCellEditor(blockedAlternatives);
    

    您可能还需要覆盖其他一些方法。我只是展示逻辑

    参考资料:

    【讨论】:

    • 感谢您的回答,尽管我采用了另一种设计,但这是一个很好的答案,将来会对我和其他人有所帮助。干杯。
    猜你喜欢
    • 2020-11-26
    • 1970-01-01
    • 2023-04-08
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    相关资源
    最近更新 更多