java-使用HashMap对JTree节点进行分组
作者:互联网
我正在尝试使用HashMap构建JTree,将Values作为主要类别,将Keys作为子类别.本质上,它将看起来像这样:
Movies
-Marvel
-The Avengers
-Guardians of the Galaxy
-James Bond
-Casino Royale
-Skyfall
现在,当我尝试构建树时,我得到了一对一的层次结构,其中为每个键分配了一个新类别,即使已经存在与String匹配的类别.看起来像这样:
Movies
-Marvel
-The Avengers
-Marvel
-Guardians of the Galaxy
下面是我的代码.如何搜索节点以确保没有重复的类别?
public class JTree extends JFrame {
private javax.swing.JTree genreTree;
private JPanel panel1;
public JTree() throws IOException{
super("Genre Search");
setContentPane(panel1);
pack();
setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
setVisible(true);
setSize(new Dimension(500,500));
genreTree.setModel(null);
HashMap<String, String> hash = new HashMap<String, String>();
hash.put("Avengers","Marvel");
hash.put("Guardians","Marvel");
hash.put("Casino Royale","James Bond");
hash.put("Skyfall","James Bond");
String genreName = "Movies";
DefaultMutableTreeNode genreMainTree = new
DefaultMutableTreeNode(genreName);
DefaultMutableTreeNode mediaTitleNode = new DefaultMutableTreeNode("");
DefaultMutableTreeNode universeTitleNode = new
DefaultMutableTreeNode("");
Set<String> keys = hash.keySet();
Collection<String> values = hash.values();
ArrayList<Map.Entry<String,String>> copy = new
ArrayList<Map.Entry<String, String>>();
copy.addAll(hash.entrySet());
for (Map.Entry<String,String> e : copy){
mediaTitleNode = new DefaultMutableTreeNode(e.getKey());
universeTitleNode = new DefaultMutableTreeNode(e.getValue());
genreMainTree.add(universeTitleNode);
universeTitleNode.add(mediaTitleNode);
}
genreTree.setModel(new DefaultTreeModel(genreMainTree));
}
}
解决方法:
How can I search through the nodes to make sure I don’t end up with any duplicate categories?
保持地图以类别为键,并以其值为节点.
Map<String, DefaultMutableTreeNode> categoryToNode = new HashMap<>();
迭代时,检查此Map是否包含类别Node:
>如果确实将子级添加到该节点
>如果未创建,则将其添加到“树和地图”中.
例如:
DefaultMutableTreeNode universeTitleNode = categoryToNode.get(e.getValue());
if (universeTitleNode == null ){
universeTitleNode = new DefaultMutableTreeNode(e.getValue());
categoryToNode.put(e.getValue(), universeTitleNode);
genreMainTree.add(universeTitleNode);
}
mediaTitleNode = new DefaultMutableTreeNode(e.getKey());
universeTitleNode.add(mediaTitleNode);
标签:jtree,hashmap,java 来源: https://codeday.me/bug/20191120/2043262.html