繁体   English   中英

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

[英]How to make a combobox, inside a jtree, show its menu?

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

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

图片

在点击框之前 在此输入图像描述

点击后框 在此输入图像描述

我试过的代码

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

我显然不希望能够编辑整个树,我只是希望能够显示组合框的菜单。 我刚刚从网上获取此代码进行测试。 有任何想法吗?

它基本上打开了菜单,但当我选择其中一个项目时,它取代了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);

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

参考文献:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM