简体   繁体   中英

Changing nodes in JTree

Could anybody, please, help me with my code! I have some data in ArrayLists, I show it whith a JTree. I want to be able to edit my data and save this in my container. Now visual part works perfect, but nothing changes inside my ArrayList. How can I reach my goal?

That's how my JTree looks like:

 public TreeNode makeTree()
    {   
        ArrayList <Factory> factories = myparser.parseXml();

        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Factories");

        for (int i=0; i<factories.size(); ++i)
        {
            Factory factory = factories.get(i);
            DefaultMutableTreeNode factory1 = new DefaultMutableTreeNode(factory.getName());
            root.add(factory1);
            for (int j=0; j<factory.getDepartments().size(); ++j)
            {
                Department department = factory.getDepartments().get(j);
                DefaultMutableTreeNode department1 = new DefaultMutableTreeNode(department.getName());
                factory1.add(department1);
                for (int k=0; k<department.getSections().size(); ++k)
                {
                    Section section = department.getSections().get(k);
                    DefaultMutableTreeNode section1 = new DefaultMutableTreeNode(section.getName());
                    department1.add(section1);
                    for (int m=0; m<section.getProducts().size(); ++m)
                    {
                        Product product = section.getProducts().get(m);
                        DefaultMutableTreeNode product1 = new DefaultMutableTreeNode(product.getId());
                        section1.add(product1);
                        DefaultMutableTreeNode product1_amount = new DefaultMutableTreeNode(product.getAmount());
                        product1.add(product1_amount);
                    }
                }
            }
        }
        return root;
    }

Here's my actionListener:

 JButton addChildButton = new JButton("Add Child");
          addChildButton.addActionListener(new
             ActionListener()
             {
                public void actionPerformed(ActionEvent event)
                {
                   DefaultMutableTreeNode selectedNode
                      = (DefaultMutableTreeNode)
                      tree.getLastSelectedPathComponent();

                   if (selectedNode == null) return;

                   DefaultMutableTreeNode newNode
                      = new DefaultMutableTreeNode("New");
                   model.insertNodeInto(newNode, selectedNode,
                      selectedNode.getChildCount());               

                   // now display new node

                   TreeNode[] nodes = model.getPathToRoot(newNode);
                   TreePath path = new TreePath(nodes);
                   tree.scrollPathToVisible(path);
                }
             });

And here are my classes on witch arralist is based on:

import java.util.ArrayList;
public class Factory {

private String name;
private ArrayList <Department> departments;

public Factory(String name, ArrayList<Department> departments)
{this.name = name; this.departments = departments;}


public String getName()
{
    return this.name;
}

public void setName(String name)
{
    this.name = name;
}

public void addDepartment(Department department)
{
    departments.add(department);
}

public ArrayList<Department> getDepartments() 
{
    return this.departments;
}

public void setDepartments(ArrayList<Department> departments) 
{
   this.departments = departments;
}

}

import java.util.ArrayList;

public class Department {

private String name;
private ArrayList <Section> sections;

public Department(String name, ArrayList<Section> sections)
{this.name = name; this.sections = sections;}

public String getName()
{
    return this.name;
}

public void setName(String name)
{
    this.name = name;
}

public void addSection(Section section)
{
    sections.add(section);
}

public ArrayList<Section> getSections() 
{
    return this.sections;
}

public void setSections(ArrayList<Section> sections) 
{
    this.sections = sections;
}

}

import java.util.ArrayList;

public class Section {

private String name;
private ArrayList<Product> products;

public Section(String name, ArrayList<Product> products)
{this.name = name; this.products = products;}

public String getName()
{
    return this.name;
}

public void setName(String name)
{
    this.name = name;
}

public void addProduct(Product product)
{
    products.add(product);
}

public ArrayList<Product> getProducts() 
{
    return this.products;
}

public void setProducts(ArrayList<Product> products) 
{
   this.products = products;
}


}



public class Product {

private String id;
private int amount;

public Product (String id, int amount){this.id = id; this.amount = amount;}

public String getId()
{
    return this.id;
}

public void setId(String id)
{
    this.id = id;
}

public int getAmount()
{
    return this.amount;
}

public void setAmount(int amount)
{
    this.amount = amount;
}

}

You add new values just to JTree nodes, but also you need to add new values to Department / Factory instance.

Try next example in which MyObject is class that represents TreeNode . "add" is button, which adds a new Object to JTree and to instance of MyObject, "print" prints to console current child objects:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

public class TestFrame extends JFrame {

    private JTree tree;
    private DefaultTreeModel model;

    public TestFrame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        init();
        pack();
        setVisible(true);
    }

    private void init() {
        TreeNode root = getNodes();
        tree = new JTree(model = new DefaultTreeModel(root));
        tree.setRootVisible(false);

        JButton add = new JButton("add new");
        add.addActionListener(getAddActionListener());

        JButton print = new JButton("print childs");
        print.addActionListener(getPrintActionListener());
        JPanel btns = new JPanel();
        btns.add(add);
        btns.add(print);

        add(new JScrollPane(tree));
        add(btns,BorderLayout.SOUTH);
    }

    private ActionListener getPrintActionListener() {
        return new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
                if (selectedNode == null){
                    return;
                }
                MyObject obj = (MyObject) selectedNode.getUserObject();
                System.out.println(obj.childs);
            }
        };
    }

    private ActionListener getAddActionListener() {
        return new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
                if (selectedNode == null){
                    return;
                }
                MyObject obj = (MyObject) selectedNode.getUserObject();
                MyObject newChild = new MyObject(obj.name+"-"+(obj.childs.size()+1));
                obj.childs.add(newChild);
                DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(newChild);
                model.insertNodeInto(newNode, selectedNode,selectedNode.getChildCount());
                TreeNode[] nodes = model.getPathToRoot(newNode);
                TreePath path = new TreePath(nodes);
                tree.scrollPathToVisible(path);
            }
        };
    }

    private TreeNode getNodes() {
        MyObject obj1 = new MyObject("1");
        MyObject obj2 = new MyObject("1-1");

        obj1.childs.add(obj2);
        obj2.childs.add(new MyObject("2-1"));
        obj2.childs.add(new MyObject("2-2"));

        obj1.childs.add(new MyObject("1-2"));
        obj1.childs.add(new MyObject("1-3"));

        DefaultMutableTreeNode root = new DefaultMutableTreeNode();
        construct(obj1,root);
        return root;
    }

    private void construct(MyObject obj1, DefaultMutableTreeNode root) {
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(obj1);
        root.add(node);
        for(MyObject o : obj1.childs){
            construct(o,node);
        }
    }

    public static void main(String... strings) {
        new TestFrame();
    }

    private class MyObject{
        private String name;
        private List<MyObject> childs = new ArrayList<>();

        public MyObject(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return name;
        }

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM