这可能是回顾旧事的好时机J树表代码,这将为您提供在第一列中呈现的树,并可以根据需要自由地将每列的单元格渲染到树节点的右侧,在您的情况下放入复选框和标签,并允许您TableCellEditors 按照您习惯的方式使用您的 JTable。警告是,虽然该链接中的代码可以工作,但它有点复杂。
还有一个替代方案。我在下面演示了一个应该更好的树表实现,称为Outline
,由 NetBeans 提供(尽管您不需要使用 NetBeans IDE 进行开发,您只需要 jar)。本文表明上手是多么容易。
我能够在大约 30 分钟内(我打字速度很慢)在 Eclipse 中模拟一个大纲树表的快速示例(将 org-netbeans-swing-outline.jar 导入到我的项目中):
private void buildFrame() {
frame = new JFrame("Demo");
frame.setSize(300, 300);
addStuffToFrame();
frame.setVisible(true);
}
private void addStuffToFrame() {
MyTreeNode top = new MyTreeNode("top");
createNodes(top);
DefaultTreeModel model = new DefaultTreeModel(top);
//here are the netBeans tree table classes
OutlineModel outlineModel =
DefaultOutlineModel.createOutlineModel(model, new MyRowModel());
Outline outline = new Outline();
outline.setRootVisible(true);
outline.setModel(outlineModel);
frame.getContentPane().add(new JScrollPane(outline));
}
private void createNodes(MyTreeNode top) {
MyTreeNode child = new MyTreeNode("child 2");
top.add(new MyTreeNode("child 1"));
child.add(new MyTreeNode("g-child1"));
child.add(new MyTreeNode("g-child2"));
child.add(new MyTreeNode("g-child3"));
top.add(child);
top.add(new MyTreeNode("child3"));
top.add(new MyTreeNode("child4"));
}
我创建一个 TreeNode 来保存Boolean
能够与JTable
的内置复选框渲染机制。
public class MyTreeNode extends DefaultMutableTreeNode {
Boolean data1 = null;
Boolean data2 = null;
String name = null;
MyTreeNode (String name) {
this.name=name;
}
void setData1(Boolean val) {data1=val;}
void setData2(Boolean val) {data2=val;}
Boolean getData1() {return data1;}
Boolean getData2() {return data2;}
String getName() {return name;}
}
netBeans RowModel 是使其成为表而不是简单的 JTree 的关键:
public class MyRowModel implements RowModel {
public Class getColumnClass(int col) {
switch (col) {
case 0: return String.class;
case 1: return Boolean.class; //these return class definitions will
case 2: return Boolean.class; //trigger the checkbox rendering
default:return null;
}
}
public int getColumnCount() {
return 3;
}
public String getColumnName(int col) {
return "";
}
public Object getValueFor(Object node, int col) {
MyTreeNode n = (MyTreeNode)node;
switch (col) {
case 0: return n.getName();
case 1: return n.getData1();
case 2: return n.getData2();
default:return null;
}
}
public boolean isCellEditable(Object node, int col) {
return col > 0;
}
public void setValueFor(Object node, int col, Object val) {
MyTreeNode n = (MyTreeNode)node;
if (col == 1) {n.setData1((Boolean)val);}
else if (col == 2) {n.setData2((Boolean)val);}
//EDIT: here is a recursive method to set all children
// selected for one of the two checkboxes as it is
// checked by the parent
for (Enumeration children = n.children();
children.hasMoreElements(); ) {
MyTreeNode child = (MyTreeNode) children.nextElement();
setValueFor(child, col, val);
}
}
}
这是成品,尽管很简单:
替代文本http://img17.imageshack.us/img17/6643/picture1hz.png
我已经更新了setValueFor
方法迭代节点的子节点,并在修改父节点时将复选框设置为选中或取消选中。