我需要将Hashmap
绑定到MutableTreeNode
,以便可以在JTree
中显示它。
我有以下代码:
static Map<String, String> form = new LinkedHashMap<String,String>();
我想这就是实现
MutableTreeNode
的方式。我只是不知道现在该如何进行操作以使“表单”的键出现在MutableTreeNode
中。public class MyNode implements MutableTreeNode {
@Override
public Enumeration children() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean getAllowsChildren() {
// TODO Auto-generated method stub
return false;
}
@Override
public TreeNode getChildAt(int childIndex) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getChildCount() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getIndex(TreeNode node) {
// TODO Auto-generated method stub
return 0;
}
@Override
public TreeNode getParent() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isLeaf() {
// TODO Auto-generated method stub
return false;
}
@Override
public void insert(MutableTreeNode arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void remove(int arg0) {
// TODO Auto-generated method stub
}
@Override
public void remove(MutableTreeNode arg0) {
// TODO Auto-generated method stub
}
@Override
public void removeFromParent() {
// TODO Auto-generated method stub
}
@Override
public void setParent(MutableTreeNode arg0) {
// TODO Auto-generated method stub
}
@Override
public void setUserObject(Object arg0) {
// TODO Auto-generated method stub
}
MutableTreeNode
正确显示正确的Key
值后,我希望能够执行以下操作:final JTree tree = new JTree();
final DefaultMutableTreeNode CustomNode = new DefaultMutableTreeNode("Custom");
DefaultTreeModel tm = new DefaultTreeModel(CustomNode);
tree.setModel(tm);
for (String str : form.keySet())
{
MyNode nod = new MyNode(str);
CustomNode.add(node);
}
tm.reload();
最佳答案
您可能需要TreeModel
接口的自定义实现。如How to Use Trees: Creating a Data Model中所述,
TreeModel
接口接受任何类型的对象作为树节点。它不需要节点由DefaultMutableTreeNode
对象表示,甚至不需要节点实现TreeNode
接口。
尽管您的Map<String, String>
并非本质上是分层的,但您可能会从GenealogyModel
,引用为here或FileTreeModel
引用为here和here的想法。