Putting properties file into a JTree rather than just displaying it

血红的双手。 提交于 2019-12-25 02:32:56

问题


This is my current code - it just displays the key pair values from my GitCommands.properties file and displays it in my GetAllProperties.java file - is it possible to sort it so it goes in to a JTree rather than just displaying it in a list type format?

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

public class GetAllProperties {
    private static JTree tree;

    public static void main(String[] args) {

        Properties properties = new Properties();
        try {
            String filename = "GitCommands.properties";
            // File file = new
            // File("/ApplicationTest/.settings/GitCommands.properties");
            FileInputStream fileInputStream = new FileInputStream(filename);

            // load properties file
            properties.load(fileInputStream);

            System.out.println("keys avialble in Properties Files are:");
            System.out.println(properties.keySet());

            System.out.println("Key Value Pairs :");
            Enumeration enumeration = properties.keys();
            while (enumeration.hasMoreElements()) {
                String key = (String) enumeration.nextElement();
                System.out.println(key + ": " + properties.get(key));
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

回答1:


you can simply populate the tree using the tree model

DefaultMutableTreeNode root = new DefaultMutableTreeNode(filename);
DefaultTreeModel treeModel = new DefaultTreeModel(root);

Enumeration enumeration = properties.keys();  
while (enumeration.hasMoreElements()) {  
    String key = (String) enumeration.nextElement();
    String nodeObj = key+" : "+properties.get(key);
    treeModel.insertNodeInto(new DefaultMutableTreeNode(nodeObj), root, 0);
}

JTree tree = new JTree(treeModel);

NOTE: the elements are not sorted... to do so, you need to push all keys into a list and sort that list

List sortedList<String> = new ArrayList<String>();
Enumeration enumeration = properties.keys();  
while (enumeration.hasMoreElements()) {  
    String key = (String) enumeration.nextElement();
    sortedList.add(key);
}
Collection.sort(sortedList);

for(String key: sortedList){
    String nodeObj = key+" : "+properties.get(key);
    // [...] same as above
}


来源:https://stackoverflow.com/questions/25399983/putting-properties-file-into-a-jtree-rather-than-just-displaying-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!