我的目标是使用JTable作为JTree节点,并且能够通过双击来编辑JTable中的单元格。渲染效果很好(Jtable as a Jtree Node),但我不知道如何编辑表格中的单个单元格。如果我将树设置为可编辑,我可以使用双击编辑节点,但我想自己编辑单元格,因为用户似乎不愿意在我用于渲染的数字前面保留“%”。如果树未设置为可编辑,则双击不执行任何操作。有没有一种简单的方法可以实现这一目标?
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();
}
}
答案 0 :(得分:1)
答案 1 :(得分:0)
您应该为数据模型添加方法isCellEditable。否则你的表格不可编辑。
看起来像这样:
@Override
public boolean isCellEditable(int row, int col)
{
return col >= 0;
}