[英]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()
,然后返回一個包含JLabel
和JComboBox
的JPanel
,類似於:
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.