문제

So I have this very interesting problem: The goal of the problem is to have a JTree, a text field and an Add button; When a node is clicked and there is text in the text field, upon pressing the add button a node is created as a child of the clicked node.

I instantiate a tree, as usual:

    tree = new JTree(treeModel);
    tree.setEditable( true );
    tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION );
    tree.setShowsRootHandles( true );

Then I set up the listeners:

tree.addMouseListener( new MouseAdapter()
    {
        @Override
        public void mouseClicked( MouseEvent e )
        {
            doMouseClicked( e );
        }
    } );

    jButton.addActionListener( new ActionListener()
    {
        @Override
        public void actionPerformed( ActionEvent e )
        {
            if(nodeIsClicked && (!jTextField.getText().isEmpty()))
            {
                DefaultMutableTreeNode y = new DefaultMutableTreeNode( jTextField.getText() );
                m.add( y );
            }
        }
    } );
}

void doMouseClicked(MouseEvent me) {
    tp = tree.getPathForLocation(me.getX(), me.getY());
    if (tp != null )
    {
        m = (DefaultMutableTreeNode) tp.getLastPathComponent();
        nodeIsClicked = true;
    }
    else
    {
        nodeIsClicked = false;
    }
}

The odd thing is, that apart from the fact that I can't quite set up the update the way I want it (to basically expand the tree to the node just created), after, say, I add 2 nodes to the root, and then another node to one of the two I have just created, when I click on the root again and try to add a new node - nothing. It gets all the way to the m.add() method, but it just doesn't add a new node.

Any ideas on how I could approach this? Any solutions that come to mind?

도움이 되었습니까?

해결책

After m.add( y ); you can use :

((DefaultTreeModel) tree.getModel()).nodesWereInserted(m,new int[]{m.getChildCount()-1});

Accordint to docs:

Invoke this method after you've inserted some TreeNodes into node. childIndices should be the index of the new elements and must be sorted in ascending order.

So that fires needed events and helps you.

Also use TreeSelectionListener instead of MouseListener as mentioned by @AndrewThompson.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top