Frage

Here is my application.

enter image description here

What I want to do is make it so that when the user's details are updated, so does it's node in the JTree. Is this possible; even though the JTree and it's rendered cells have already been created?

I need an example of updating a rendered cell even after it has already been created.

Here is my View code:

void createTree() {

    rootNode = new DefaultMutableTreeNode("users");

    for (User user : listOfUsers) {

        String id = user.getId();
        File file = new File(id);
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(file);
        rootNode.add(node);
    }

    treeModel = new DefaultTreeModel(rootNode);
    tree = new JTree(rootNode);
}

void addTreeModelListener(TreeModelListener a) {

    treeModel.addTreeModelListener(a);
}

void repaintTree() {

    treeModel.reload();
    tree.revalidate();
    tree.repaint();
}

And here is my Controller code:

view.addTreeModelListener(new MyTreeModelListener());

class MyTreeModelListener implements TreeModelListener {
    public void treeNodesChanged(TreeModelEvent e) {

        DefaultMutableTreeNode node;
        node = (DefaultMutableTreeNode)(e.getTreePath().getLastPathComponent());

        int index = e.getChildIndices()[0];
        node = (DefaultMutableTreeNode)(node.getChildAt(index));

        System.out.println("The user has finished editing the node.");
        System.out.println("New value: " + node.getUserObject());       
    }

    public void treeNodesInserted(TreeModelEvent e) {}
    public void treeNodesRemoved(TreeModelEvent e) {}
    public void treeStructureChanged(TreeModelEvent e) {}
}

The idea is after the changes to the objects have been made, I call the repaintTree() method. After looking over the code now, I think the problem lies in the fact that I'm changing the object details and not the node details, but that's just a hunch.

Please reply soon, many thanks.

War es hilfreich?

Lösung

Swing uses MVC architecture.

So data contained in the tree and the logic for rendering are completely decoupled and independent.

You can simply change contents of the tree without worrying using this Oracle Tutorial. Just don't forget to call revalidate() and repaint() method after updating.

Good luck.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top