我基本上有一个 JTree,我可以在其中显示某些信息。在其中一个“子树”中,我得到了一个面板,它由一个带有 GridLayout(0,2) 的面板和一个 JPanel 以及一个组合框组成。
我注意到我的树中没有任何组件对输入使用react。这当然意味着当我试图点击它时,我的组合框不会有反应。我试图实现一个默认的单元格编辑器,它可以工作但不像我想要的那样。它基本上打开了菜单,但是当我选择其中一项时,它替换了 JLabel,因此只有组合框可见。
图片
点击方框前
点击框后
我尝试过的代码
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
其中包含 JLabel
和 JComboBox
,类似于:
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/