Jose Lara
Jose Lara

Reputation: 65

JAVA - How to access objects of ArrayList from JTree

I am having issues accessing the elements of my ArrayList just clicking in the corresponding node. This is the first time I am using this, I have searched for a lot of different tutorials but I could not solve my issue. This is what I have so far:

Everytime that I add or remove an element from the ArrayList, I use refreshTree() method in order to get an updated version of my ArrayList.

In my Menu class I have also different JTextPanel for the different attributes of the animals.

What I need to do (I will not copy the code I have right now, because I think has not sense) is to be able to click in one node, so the different attributes of the animal are loaded in the JTextPanel, so if I modify the values, they will be changed in the object as well.

I know I should use something like:

int value = textPanel.getText();

And then use the setters of my class Animal.

My problem is how I access to that specific animal just clicking in the JTree?

Upvotes: 1

Views: 930

Answers (1)

Beniton Fernando
Beniton Fernando

Reputation: 1533

You can do like below. Hope it helps you to progress.

JTree tree = new JTree();
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Animals");
DefaultTreeModel model = new DefaultTreeModel(root);

tree.setModel(model);
root.add(new DefaultMutableTreeNode(new Animal("Dog","ACS")));
root.add(new DefaultMutableTreeNode(new Animal("Cat","BCS")));
root.add(new DefaultMutableTreeNode(new Animal("Lion","FCS")));

DefaultTreeSelectionModel sModel = new DefaultTreeSelectionModel(); 

sModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setSelectionModel(sModel);
tree.addTreeSelectionListener(new TreeSelectionListener() {

    @Override
    public void valueChanged(TreeSelectionEvent selection) {
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)selection.getPath().getLastPathComponent();
        if(selectedNode.isLeaf()) {
            Animal animal = (Animal)selectedNode.getUserObject();
        }
    }
});

Upvotes: 2

Related Questions