使用文本文件中的数据创建JTree

时间:2021-02-08 12:36:54

How can I create a JTree using data from a .txt file? The text file is formatted as follows:

如何使用.txt文件中的数据创建JTree?文本文件的格式如下:

Root Node
        Category A
            Sub-Category A1
                Item A1.0
                Item A1.1
                Item A1.2
            Sub-Category A2
                Item A2.0
                Item A2.1
                Item A2.2       
        Category B
            Sub-Category B1
                Item B1.0
                Item B1.1
            Sub-Category B2
                Item B2.0
                Item B2.1
            Sub-Category B3
                Item B3.0
                Item B3.1
                Sub-Sub-Category B3_1
                    Item B3_1.0
                    Item B3_1.1
        Category C
            ... etc

The .txt file contains over 700 lines.

.txt文件包含700多行。

4 个解决方案

#1


3  

If the txt will have tabular (or spaces) well formatted, you can read the file line by line, count the number of spaces and then add the node to the tree as needed.

如果txt将具有格式良好的表格(或空格),则可以逐行读取文件,计算空格数,然后根据需要将节点添加到树中。

You can read more about JTree in java tutorial How to Use Trees.

您可以在Java教程如何使用树中阅读有关JTree的更多信息。

But as @Abhishekkumar said,what have you tried? Why you can't do it? Complete your answer and don't make others do your work.

但正如@Abhishekkumar所说,你有什么尝试?你为什么不能这样做?完成你的答案,不要让别人做你的工作。

#2


1  

Just as PhoenixS has mentioned in his answer above, the procedure involves the following steps:

正如PhoenixS在上面的回答中提到的,该过程涉及以下步骤:

  1. Read the .txt file line by line. In this example we use BufferedReader in conjunction with InputStreamReader OR FileReader, depending on whether we are reading the .txt file as a resource or from the File System respectively.
  2. 逐行读取.txt文件。在此示例中,我们将BufferedReader与InputStreamReader或FileReader结合使用,具体取决于我们是将.txt文件作为资源读取还是分别从文件系统读取。

  3. Depending on the formatting of the .txt file, use the delimiter to determine the hierarchy level of each line as it is being read. Use this to create the relevant nodes of your Jtree. In this case the .txt file is tab-delimited, with the number of tabs indicating the hierarchy level.
  4. 根据.txt文件的格式,使用分隔符确定每行读取时的层次结构级别。使用它来创建Jtree的相关节点。在这种情况下,.txt文件以制表符分隔,并带有指示层次结构级别的选项卡数。

Here is the TreeFromTextFile class I wrote:

这是我写的TreeFromTextFile类:

/*
 * File: TreeFromTextFile.java
 * Created 2013-02-06
 * This Class creates a JTree using data from a Specially formatted text File.
 * The supplied text file is tab-delimited, as illustrated at:
 * https://*.com/questions/14724014/create-jtree-using-data-from-text-file
 * 
 * You can use either InputStreamReader to read thetext file as a resource
 * or use FileReader to read the text file from the file System
 */


import java.io.BufferedReader;
//import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;

/**
 * @author engineervix
 *
 */
public class TreeFromTextFile {

private BufferedReader in;
private LineNumberReader ln;
private String line;    //value of a line in the text file
private String root;    //value to be used for the root Node of our JTree                         
private String filename = "TheTextFile.txt";
private String encoding = "UTF-8";
private DefaultMutableTreeNode top;
private JTree tree;

public TreeFromTextFile() {
    getRootNode();
    top = new DefaultMutableTreeNode(root);
    createNodes(top);

    //Create a tree that allows one selection at a time.
    tree = new JTree(top);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
}

//this method reads the file and prints all the lines to standard output
//for testing purposes
public void readFile() {
    try {
        //in = new BufferedReader(new FileReader("Path\\To\\File.txt"));
        in = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename), encoding));

        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

//this method reads the first line in the text file and assigns it 
//to the root variable which will be used for the root node of our JTree
private void getRootNode() {
    try {
        //in = new BufferedReader(new FileReader("Path\\To\\File.txt"));
        in = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename), encoding));
        ln = new LineNumberReader(in);

        if (ln.getLineNumber() == 0) {
            root = ln.readLine();
            //System.out.println(root);
        }

        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * this method counts the number of occurrences of a given
 * <code>char</code> in the Specified
 * <code>String</code> source:
 * https://*.com/questions/275944/how-do-i-count-the-number-of-occurrences-of-a-char-in-a-string
 */
private int countOccurrences(String haystack, char needle) {
    int count = 0;
    for (int i = 0; i < haystack.length(); i++) {
        if (haystack.charAt(i) == needle) {
            count++;
        }
    }
    return count;
}

//create the Nodes
private void createNodes(DefaultMutableTreeNode top) {
    DefaultMutableTreeNode category = null;     // Level 1 in Hierarchy
    DefaultMutableTreeNode subCategory = null;  // Level 2 in Hierarchy
    DefaultMutableTreeNode leaf = null;         // Level 3 in Hierarchy    

    try {
        //in = new BufferedReader(new FileReader("Path\\To\\File.txt"));
        in = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename), encoding));

        while ((line = in.readLine()) != null) {
            if (countOccurrences(line, '\t') == 1) {
                category = new DefaultMutableTreeNode(line);
                top.add(category);
            } else if (countOccurrences(line, '\t') == 2) {
                subCategory = new DefaultMutableTreeNode(line);
                category.add(subCategory);
            } else if (countOccurrences(line, '\t') == 3) {
                leaf = new DefaultMutableTreeNode(line);
                subCategory.add(leaf);
            } //continue the else...if - if you have more levels
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

    public JTree getTree() {
        return tree;
    }
}

To test the above, I wrote the TreeFromTextFileDemo class, which is as shown below:

为了测试上面的内容,我编写了TreeFromTextFileDemo类,如下所示:

/*
 * Requires TreeFromTextFile.java
 */

import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;

/**
 * @author engineervix
 */
public class TreeFromTextFileDemo {

private static TreeFromTextFile tr = new TreeFromTextFile();

public static void main(String[] args) {
    JFrame frame = new JFrame("Demo | Creating JTree From File.txt");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = frame.getContentPane();

    JTree t = tr.getTree();

    content.add(new JScrollPane(t), BorderLayout.CENTER);
    frame.setSize(275, 300);
    frame.setLocationByPlatform(true);
    frame.setVisible(true);

    }
}

The following screenshot illustrates the output. You can use this file as a sample text file.

以下屏幕截图显示了输出。您可以将此文件用作示例文本文件。

使用文本文件中的数据创建JTree

#3


0  

If you want it more flexible, don't hard code the levels. Simply retain the last node at any given level using a Map. As you traverse the items in your file, you will have access to any parent node via the map. Here is the code ...

如果您希望它更灵活,请不要对级别进行硬编码。只需使用Map保留任何给定级别的最后一个节点。当您遍历文件中的项目时,您将可以通过地图访问任何父节点。这是代码......

public class StructureBuilder {

    public static final DefaultMutableTreeNode getTreeNode(File file) throws IOException  {

        DefaultMutableTreeNode rootNode = null;
        Map<Integer, DefaultMutableTreeNode> levelNodes = new HashMap<Integer, DefaultMutableTreeNode>();
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line;

        while( (line = reader.readLine()) != null ) {

            int level = getLevel(line);
            String nodeName = getNodeName(line, level);
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(nodeName);               
            levelNodes.put(level, node);
            DefaultMutableTreeNode parent = levelNodes.get(level - 1);

            if( parent != null ) {
                parent.add(node);
            }
            else {
                rootNode = node;
            }
        }    
        reader.close();
        return rootNode;
    }

    private static final int getLevel(String line) {

        int level = 0;
        for ( int i = 0; i < line.length(); i++ ) {
            char c = line.charAt(i);
            if( c == '\t') {
                level++;
            }
            else {
                break;
            }
        }
        return level;
    }

    private static final String getNodeName(String line, int level) {
        return line.substring(level);
    }      
}

#4


0  

I had a similar problem and wrote a general builder class for this. It takes our source data Collection and a Hierarchy description and bingo. TreeModel.

我遇到了类似的问题,并为此编写了一个通用的构建器类。它需要我们的源数据集合和层次结构描述和宾果游戏。 TreeModel的。

You can also swap the structure around in real time.

您还可以实时交换结构。

https://*.com/a/29823595/4824123

Project: https://github.com/mnrussell/collectionTreeModel

Hope this helps

希望这可以帮助

#1


3  

If the txt will have tabular (or spaces) well formatted, you can read the file line by line, count the number of spaces and then add the node to the tree as needed.

如果txt将具有格式良好的表格(或空格),则可以逐行读取文件,计算空格数,然后根据需要将节点添加到树中。

You can read more about JTree in java tutorial How to Use Trees.

您可以在Java教程如何使用树中阅读有关JTree的更多信息。

But as @Abhishekkumar said,what have you tried? Why you can't do it? Complete your answer and don't make others do your work.

但正如@Abhishekkumar所说,你有什么尝试?你为什么不能这样做?完成你的答案,不要让别人做你的工作。

#2


1  

Just as PhoenixS has mentioned in his answer above, the procedure involves the following steps:

正如PhoenixS在上面的回答中提到的,该过程涉及以下步骤:

  1. Read the .txt file line by line. In this example we use BufferedReader in conjunction with InputStreamReader OR FileReader, depending on whether we are reading the .txt file as a resource or from the File System respectively.
  2. 逐行读取.txt文件。在此示例中,我们将BufferedReader与InputStreamReader或FileReader结合使用,具体取决于我们是将.txt文件作为资源读取还是分别从文件系统读取。

  3. Depending on the formatting of the .txt file, use the delimiter to determine the hierarchy level of each line as it is being read. Use this to create the relevant nodes of your Jtree. In this case the .txt file is tab-delimited, with the number of tabs indicating the hierarchy level.
  4. 根据.txt文件的格式,使用分隔符确定每行读取时的层次结构级别。使用它来创建Jtree的相关节点。在这种情况下,.txt文件以制表符分隔,并带有指示层次结构级别的选项卡数。

Here is the TreeFromTextFile class I wrote:

这是我写的TreeFromTextFile类:

/*
 * File: TreeFromTextFile.java
 * Created 2013-02-06
 * This Class creates a JTree using data from a Specially formatted text File.
 * The supplied text file is tab-delimited, as illustrated at:
 * https://*.com/questions/14724014/create-jtree-using-data-from-text-file
 * 
 * You can use either InputStreamReader to read thetext file as a resource
 * or use FileReader to read the text file from the file System
 */


import java.io.BufferedReader;
//import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;

/**
 * @author engineervix
 *
 */
public class TreeFromTextFile {

private BufferedReader in;
private LineNumberReader ln;
private String line;    //value of a line in the text file
private String root;    //value to be used for the root Node of our JTree                         
private String filename = "TheTextFile.txt";
private String encoding = "UTF-8";
private DefaultMutableTreeNode top;
private JTree tree;

public TreeFromTextFile() {
    getRootNode();
    top = new DefaultMutableTreeNode(root);
    createNodes(top);

    //Create a tree that allows one selection at a time.
    tree = new JTree(top);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
}

//this method reads the file and prints all the lines to standard output
//for testing purposes
public void readFile() {
    try {
        //in = new BufferedReader(new FileReader("Path\\To\\File.txt"));
        in = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename), encoding));

        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

//this method reads the first line in the text file and assigns it 
//to the root variable which will be used for the root node of our JTree
private void getRootNode() {
    try {
        //in = new BufferedReader(new FileReader("Path\\To\\File.txt"));
        in = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename), encoding));
        ln = new LineNumberReader(in);

        if (ln.getLineNumber() == 0) {
            root = ln.readLine();
            //System.out.println(root);
        }

        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * this method counts the number of occurrences of a given
 * <code>char</code> in the Specified
 * <code>String</code> source:
 * https://*.com/questions/275944/how-do-i-count-the-number-of-occurrences-of-a-char-in-a-string
 */
private int countOccurrences(String haystack, char needle) {
    int count = 0;
    for (int i = 0; i < haystack.length(); i++) {
        if (haystack.charAt(i) == needle) {
            count++;
        }
    }
    return count;
}

//create the Nodes
private void createNodes(DefaultMutableTreeNode top) {
    DefaultMutableTreeNode category = null;     // Level 1 in Hierarchy
    DefaultMutableTreeNode subCategory = null;  // Level 2 in Hierarchy
    DefaultMutableTreeNode leaf = null;         // Level 3 in Hierarchy    

    try {
        //in = new BufferedReader(new FileReader("Path\\To\\File.txt"));
        in = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename), encoding));

        while ((line = in.readLine()) != null) {
            if (countOccurrences(line, '\t') == 1) {
                category = new DefaultMutableTreeNode(line);
                top.add(category);
            } else if (countOccurrences(line, '\t') == 2) {
                subCategory = new DefaultMutableTreeNode(line);
                category.add(subCategory);
            } else if (countOccurrences(line, '\t') == 3) {
                leaf = new DefaultMutableTreeNode(line);
                subCategory.add(leaf);
            } //continue the else...if - if you have more levels
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

    public JTree getTree() {
        return tree;
    }
}

To test the above, I wrote the TreeFromTextFileDemo class, which is as shown below:

为了测试上面的内容,我编写了TreeFromTextFileDemo类,如下所示:

/*
 * Requires TreeFromTextFile.java
 */

import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;

/**
 * @author engineervix
 */
public class TreeFromTextFileDemo {

private static TreeFromTextFile tr = new TreeFromTextFile();

public static void main(String[] args) {
    JFrame frame = new JFrame("Demo | Creating JTree From File.txt");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = frame.getContentPane();

    JTree t = tr.getTree();

    content.add(new JScrollPane(t), BorderLayout.CENTER);
    frame.setSize(275, 300);
    frame.setLocationByPlatform(true);
    frame.setVisible(true);

    }
}

The following screenshot illustrates the output. You can use this file as a sample text file.

以下屏幕截图显示了输出。您可以将此文件用作示例文本文件。

使用文本文件中的数据创建JTree

#3


0  

If you want it more flexible, don't hard code the levels. Simply retain the last node at any given level using a Map. As you traverse the items in your file, you will have access to any parent node via the map. Here is the code ...

如果您希望它更灵活,请不要对级别进行硬编码。只需使用Map保留任何给定级别的最后一个节点。当您遍历文件中的项目时,您将可以通过地图访问任何父节点。这是代码......

public class StructureBuilder {

    public static final DefaultMutableTreeNode getTreeNode(File file) throws IOException  {

        DefaultMutableTreeNode rootNode = null;
        Map<Integer, DefaultMutableTreeNode> levelNodes = new HashMap<Integer, DefaultMutableTreeNode>();
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line;

        while( (line = reader.readLine()) != null ) {

            int level = getLevel(line);
            String nodeName = getNodeName(line, level);
            DefaultMutableTreeNode node = new DefaultMutableTreeNode(nodeName);               
            levelNodes.put(level, node);
            DefaultMutableTreeNode parent = levelNodes.get(level - 1);

            if( parent != null ) {
                parent.add(node);
            }
            else {
                rootNode = node;
            }
        }    
        reader.close();
        return rootNode;
    }

    private static final int getLevel(String line) {

        int level = 0;
        for ( int i = 0; i < line.length(); i++ ) {
            char c = line.charAt(i);
            if( c == '\t') {
                level++;
            }
            else {
                break;
            }
        }
        return level;
    }

    private static final String getNodeName(String line, int level) {
        return line.substring(level);
    }      
}

#4


0  

I had a similar problem and wrote a general builder class for this. It takes our source data Collection and a Hierarchy description and bingo. TreeModel.

我遇到了类似的问题,并为此编写了一个通用的构建器类。它需要我们的源数据集合和层次结构描述和宾果游戏。 TreeModel的。

You can also swap the structure around in real time.

您还可以实时交换结构。

https://*.com/a/29823595/4824123

Project: https://github.com/mnrussell/collectionTreeModel

Hope this helps

希望这可以帮助