使用HashMap对JTree节点进行分组

时间:2015-05-09 23:12:52

标签: 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));

    }

 }

1 个答案:

答案 0 :(得分:3)

  

如何搜索节点以确保我最终没有任何重复的类别?

保持地图键入类别,并使用它的节点进行评估。

Map<String, DefaultMutableTreeNode> categoryToNode = new HashMap<>();

迭代时,检查此Map是否包含类别Node:

  1. 如果确实将Child添加到该节点
  2. 如果没有创建一个并将其添加到树和地图中。
  3. 例如:

    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);