java - 如何使用 JTree 从文件创建 TreeView ?

标签 java swing jtree

我有一个文件 abc.csv,它是我的 bom( Material list )文件。我需要使用该文件来使用 Jtree 制作 TreeView 。我的文件有这样的数据:

PARENT_NAME     QUANTITY        COMPONENT_NAME
HOLDER          1               BODY
HOLDER          1               PTRY_GASKET
HOLDER          1               PTRY
HOLDER          1               DISC
HOLDER          1               GUIDE_SET
HOLDER          1               STEM
HOLDER          1               COV_FLG
HOLDER          1               FOLLOW_FLG

.... other entries here

这是我在 gist 中的完整文件因为它是一个非常大的文件,所以我无法将其粘贴到此处。

由于我最近开始使用 JTree,所以我有点困惑它是如何工作的。到目前为止我已经得到了以下代码:

public static void main(String[] args) {
    JFrame frame = new JFrame("FileTree");
    frame.setForeground(Color.black);
    frame.setBackground(Color.lightGray);
    Container cp = frame.getContentPane();

    if (args.length == 0) {
        cp.add(new FileTree(new File("abc.csv")));
    }

    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public FileTree(File dir) {
    setLayout(new BorderLayout());

    // Now how do I make a tree list with all the nodes, and make it a JTree from my bom

}

最佳答案

您可以基于 DefaultTreeModel 创建自定义 TreeModel 并使用您的数据填充它,如下例所示:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;

@SuppressWarnings("serial")
public class FileTree extends JFrame
{
    private JTree tree;
    private Path path;

    public FileTree(Path path)
    {
        this.path = path;
        setTitle("File Tree");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initializeComponents();
        pack();
        setVisible(true);
    }

    public void initializeComponents()
    {
        try
        {
            tree = new JTree(new CustomTreeModel(
                    new DefaultMutableTreeNode("Data"), path));
        }
        catch (IOException e)
        {
            JOptionPane.showMessageDialog(this,
                    "Error while reading input file.", "error",
                    JOptionPane.ERROR_MESSAGE);
        }
        tree.setRootVisible(false);
        add(new JScrollPane(tree));
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    UIManager.setLookAndFeel(
                            "javax.swing.plaf.nimbus.NimbusLookAndFeel");
                }
                catch (ClassNotFoundException | InstantiationException
                        | IllegalAccessException
                        | UnsupportedLookAndFeelException e)
                {
                }
                String path = "/home/mohamed/Desktop/abc.csv";
                if (args.length > 0)
                {
                    path = args[0];
                }
                new FileTree(Paths.get(path));
            }
        });
    }
}

class CustomTreeModel extends DefaultTreeModel
{
    private static final long serialVersionUID = -274517614354269449L;

    public CustomTreeModel(TreeNode root, Path path) throws IOException
    {
        super(root);
        try (BufferedReader br = new BufferedReader(
                new FileReader(path.toFile())))
        {
            String s = null;
            DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) root;
            int skipFirstLine = -1;
            List<String> items = new ArrayList<>();

            DefaultMutableTreeNode parentName;
            DefaultMutableTreeNode quantity;
            DefaultMutableTreeNode componentName;

            while ((s = br.readLine()) != null)
            {
                if (skipFirstLine == -1)
                {
                    skipFirstLine = 0;
                    continue;
                }

                items.addAll(Arrays.asList(s.split("\\s")));
                items.removeAll(Arrays.asList(""));

                if (items.size() == 3)
                {
                    parentName = new DefaultMutableTreeNode(items.get(0));
                    parentName.setAllowsChildren(false);
                    quantity = new DefaultMutableTreeNode(items.get(1));
                    quantity.setAllowsChildren(false);
                    componentName = new DefaultMutableTreeNode(items.get(2));

                    componentName.add(parentName);
                    componentName.add(quantity);

                    rootNode.add(componentName);
                }
                items.clear();
            }
            setRoot(rootNode);
        }
        catch (IOException e)
        {
            throw e;
        }
    }
}

结果如下:

enter image description here

关于java - 如何使用 JTree 从文件创建 TreeView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34938879/

相关文章:

java - Gradle获取zip fullpathname以通过ssh上传

java - Guava 中 Supplier<T> 的倒数

Java 小程序布局和操作处理程序问题

java - JTable/JXTable 如何设置列宽?

java - 如何在应用 RowFilter 过滤后禁用 jtable 中的列标题排序

java - 使用JTree获取Java中每个子类和兄弟类的名称

java - 用包列表填充树的快速而肮脏的方法

java - map API key 在 Android 应用程序中不起作用

java - 小程序 war 项目在 jar 中找不到小程序类

java - 为 JTree 实现工具提示的最佳方式?