java - 如何在 jtree 中制作一个组合框,显示其菜单?

标签 java swing jcombobox jtree

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

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

图片

点击方框前enter image description here

点击框后enter image description here

我尝试过的代码

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

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

最佳答案

It basically opened the menu but when I selected one of the items it replaced the JLabel so only the combobox was visible.

这就是您所期望的,因为这就是 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()然后返回 JPanel其中包含 JLabelJComboBox ,类似于:

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);

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

引用资料:

关于java - 如何在 jtree 中制作一个组合框,显示其菜单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12028375/

相关文章:

java - 为什么 12 :20 PM parse to 0:20 on the next day?

java - 通过使用 Field 对象设置原始数据类型

java - 自定义上传方法dropzone和angularjs

java - 写入值并单击按钮打开浏览器

java - JComboBox 设置 selectedItem 不起作用

java - 如何在 JTextField 中使用 2 个 JComboBox 中的值?

java - Integer.parseInt(scanner.nextLine()) 与 scanner.nextInt()

java - 删除JTable的列数

java - Netbeans 中的设计 View 无法加载

java - 如何获取已写入可编辑JComboBox 中的值?