gpt4 book ai didi

java - 编辑 JTable 单元格,作为 JTree 节点

转载 作者:行者123 更新时间:2023-12-01 14:31:29 27 4
gpt4 key购买 nike

我的目标是使用 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();
}

}

最佳答案

关于java - 编辑 JTable 单元格,作为 JTree 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16833841/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com