我的目标是使用 JTable 作为 JTree 节点,并能够通过双击 JTable 中的单元格来编辑它们。渲染效果很好(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();
}
}