Reputation: 65
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:
class Animal
: Just constructor with diffrent arguments, setters and getters.class MainClass
: ArrayList of animal. Main is running here.class Menu
: JFrame designed with NetBeans. To get the elements of the ArrayList I use the following code:
public void refreshTree(){
root = new DefaultMutableTreeNode("Animals");
children1 = new DefaultMutableTreeNode("Carnivores");
root.add(children1);
mainTree = new JTree(root);
List<Animal> animals = mainClass.returnList();
for(Animal animal: animals){
DefaultMutableTreeNode node = new DefaultMutableTreeNode(animal);
children1.add(node);
}
jScrollPane2.setViewportView(mainTree);
}
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
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