我的目標是將JTable用作JTree節點,並且能夠通過雙擊它們來編輯JTable中的單元格。渲染效果很好(Jtable as a Jtree Node),但我不知道如何編輯表格中的單個單元格。如果我將樹設置爲可編輯,則可以使用雙擊來編輯節點,但我想自己編輯單元格,因爲用戶似乎不願意在用於渲染的數字前面保留「%」。如果樹未設置爲可編輯雙擊,則不執行任何操作。有沒有簡單的方法來完成這個?編輯JTable單元,作爲JTree節點
public class TreeWithCellRenderer {
static class MyCellRenderer implements TreeCellRenderer {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
String command = (String) ((DefaultMutableTreeNode) value).getUserObject();
final String[] params = command.split("%");
JTable table = new JTable();
table.setModel(new DefaultTableModel() {
private static final long serialVersionUID = 1L;
@Override
public int getRowCount() {
return 1;
}
@Override
public int getColumnCount() {
return params.length;
}
@Override
public Object getValueAt(int row, int column) {
return params[column];
}
});
return table;
}
}
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("JTreeTutorial");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Tree components
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
DefaultMutableTreeNode cmd1 = new DefaultMutableTreeNode("name %1");
DefaultMutableTreeNode cmd2 = new DefaultMutableTreeNode("name %1 %2");
root.add(cmd1);
root.add(cmd2);
JTree jTree = new JTree(root);
//Don't like it too much, as it makes you edit the whole node, not cells
//jTree.setEditable(true);
jTree.setCellRenderer(new MyCellRenderer());
JScrollPane scroolPane = new JScrollPane(jTree);
frame.add(scroolPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGUI();
}
}
感謝。我試圖遵循http://stackoverflow.com/questions/12642792/easy-and-fast-jtree-cell-editor中的例子,但是這允許我編輯樹狀單元格,這是整行,我想編輯此行中只有一個單元格。你能指出一個例子嗎?我是Swing的初學者。 – dalvarezmartinez1