将属性文件放入JTree而不是仅显示它

时间:2014-08-20 08:22:27

标签: java swing jtree properties-file

这是我当前的代码 - 它只显示我的GitCommands.properties文件中的密钥对值,并将其显示在我的GetAllProperties.java文件中 - 是否可以对其进行排序,使其进入JTree而不是仅显示它以列表类型格式?

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 个答案:

答案 0 :(得分:2)

您可以使用树模型

简单地填充树
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);

注意:元素未排序......为此,您需要将所有键推入列表并对列表进行排序

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
}