从JTree添加和删除节点 [英] Adding and removing nodes from a JTree

查看:162
本文介绍了从JTree添加和删除节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常基本的JTree.由于我很着急,如果不需要TreeModel,我宁愿不使用它.我写了一个SSCCE来揭露这个问题:

I have a very basic JTree. As I am on a rush, I'd prefer not to use TreeModel if it is not needed. I wrote a SSCCE to expose the problem:

有时我添加一个节点.其他时候我将其删除.当我按Add时,正确添加了一个节点.当我按下Remove时,应该删除该节点,但不会删除.另外,如果我尝试添加多个节点,则树仅与我添加的第一个节点保持一致.

Sometimes I add a node. Other times I remove them. When I push Add, a node is correctly added. When I push Remove, it is supposed to remove the node, but it doesn't. Also, if I try adding more than one node, the tree stays with just the first node I added.

我为JTree写了一个更新方法,首先擦除从根节点挂起的所有节点,然后查看必须创建的节点和子节点.

I wrote an update method for the JTree, where I first erase all the nodes hanging from the root node, and then I look at which nodes and sub-nodes I have to create.

除了不使用TreeModel来对树进行操作之外,我在这里做错了什么?

What I am doing wrong here, apart from not using a TreeModel to operate into the tree?

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;


public class TreeTest {
    private JFrame myFrame;
    private JTree myTree;
    private JButton addButton, removeButton;

    private int numberOfNodes;
    private DefaultMutableTreeNode rootNode;

    private ArrayList<String> graphicIDS;
    private ArrayList<String> graphicInfo;

    public static void main (String [ ] args){
        new TreeTest();
    }

    public TreeTest() {
        graphicIDS = new ArrayList<String>();
        numberOfNodes = 0;
        graphicInfo = new ArrayList<String>();
        graphicInfo.add("Info A");
        graphicInfo.add("Info B");
        graphicInfo.add("Info C");
        graphicInfo.add("Info D");

        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        myFrame = new JFrame("JTree test");
        myFrame.setResizable(false);
        myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        c.fill = GridBagConstraints.BOTH;
        c.anchor = GridBagConstraints.NORTH;
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 2;
        c.insets = new Insets(5,5,5,5);

        rootNode = new DefaultMutableTreeNode("Root node");
        myTree = new JTree(rootNode);
        myTree.setPreferredSize(new Dimension(200, 500));
        panel.add(myTree, c);

        c.gridwidth = 1;
        c.gridy++;
        removeButton = new JButton("Remove");
        removeButton.setEnabled(false);
        removeButton.addActionListener(new ActionListener (){
            @Override
            public void actionPerformed(ActionEvent e) {    
                System.out.println("Removed curve "+(graphicIDS.size()));
                graphicIDS.remove(graphicIDS.size()-1);
                numberOfNodes--;
                updateMeasurementsTree();
            }
        });
        panel.add(removeButton, c);

        c.gridx++;
        addButton = new JButton("Add");
        addButton.addActionListener(new ActionListener (){
            @Override
            public void actionPerformed(ActionEvent e) {
                graphicIDS.add("Curve "+(numberOfNodes+1));
                System.out.println("Added curve "+(numberOfNodes+1));
                numberOfNodes++;
                updateMeasurementsTree();
            }
        });
        panel.add(addButton, c);

        myFrame.getContentPane().add(panel);
        myFrame.pack();
        myFrame.setVisible(true);
    }

    public void updateMeasurementsTree(){
        rootNode.removeAllChildren();

        for(int i=0; i<numberOfNodes;i++){  
            String idString = graphicIDS.get(i);
            DefaultMutableTreeNode idNode = new DefaultMutableTreeNode("Graphic "+idString);
            rootNode.add(idNode);
            int randomValue = (int) Math.floor(Math.random()*graphicInfo.size());
            String infoString = graphicInfo.get(randomValue);
            DefaultMutableTreeNode infoNode = new DefaultMutableTreeNode("Info "+infoString);
            idNode.add(infoNode);
        }
        if(numberOfNodes==0) removeButton.setEnabled(false);
        else{
            removeButton.setEnabled(true);
            expandAll();
        }
    }

    public void expandAll() {
        int row = 0;
        while (row < myTree.getRowCount()) {
          myTree.expandRow(row);
          row++;
        }
    }
}

推荐答案

我不知道为什么要删除并重新创建所有节点.

I don't know why you are deleting and recreating all the nodes.

应始终通过模型进行更新.您有两种选择:

Update should always be done through the model. You have a couple of choices:

直接更新模型:

DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
model.insertNodeInto(new DefaultMutableTreeNode("another_child"), root, root.getChildCount());

更新树节点,然后通知模型:

Update the tree nodes and then notify the model:

DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode)model.getRoot();
root.add(new DefaultMutableTreeNode("another_child"));
model.reload(root);

删除节点也是如此.

DefaultTreeModel具有removeNodeFromParent(...),它将直接更新模型.

The DefaultTreeModel has a removeNodeFromParent(...) which will update the model directly.

或者您可以使用DefaultMutableTreeNode类的remove(...)方法.在这种情况下,您需要执行reload().

Or you can use the remove(...) method of the DefaultMutableTreeNode class. In which case you would need to do the reload().

这篇关于从JTree添加和删除节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆