如何修改分配给JTree的对象?

时间:2014-03-19 03:13:36

标签: java jtree

这是我的NodeType类。每当我创建一个新的jtree节点时,我都会创建一个NodeType

的实例
public class NodeType {

    private String nodeType ;

    public NodeType (String nodeType ) {
        this.nodeType = nodeType ;
    }

    public String getNodeType() {
        return this.nodeType ;
    }
    public void setNodeType (String nodeType)   {
        this.nodeType = nodeType   ;
    }

}

我想保存与节点

关联的修改对象
btnSave = new JButton("Save");
    btnSave.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) { 
             DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                     DynamicTree.tree.getLastSelectedPathComponent();

      String txt = desc.getTxt()  ;
  Object nodeInfo = node.getUserObject();
  if (node.isLeaf()) {
     ((NodeType) nodeInfo).setNodeType(txt  );     

DefaultTreeModel model =(DefaultTreeModel)DynamicTree.tree.getModel();           model.nodeChanged(node);
      }             }         });

但是上面的“保存”按钮不起作用

1 个答案:

答案 0 :(得分:1)

我从How to use trees偷走了示例并修改了它以允许我更改节点的用户对象

主要更新在更改按钮...

中完成
JButton change = new JButton("Change");
change.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();

        if (node == null) {
            return;
        }

        Object nodeInfo = node.getUserObject();
        if (node.isLeaf()) {
            BookInfo book = (BookInfo) nodeInfo;
            book.bookName = "New Name";
            ((DefaultTreeModel)tree.getModel()).nodeChanged(node);
        }
        if (DEBUG) {
            System.out.println(nodeInfo.toString());
        }
    }
});

因此,正如您所看到的,我更改了book.bookName,这是节点的用户对象,只需调用((DefaultTreeModel)tree.getModel()).nodeChanged(node);即可更新视图...

Before After

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;

import java.net.URL;
import javax.swing.JButton;
import javax.swing.tree.DefaultTreeModel;

public class TreeDemo extends JPanel {

    private JTree tree;
    private static boolean DEBUG = false;

    //Optionally play with line styles.  Possible values are
    //"Angled" (the default), "Horizontal", and "None".
    private static boolean playWithLineStyle = false;
    private static String lineStyle = "Horizontal";

    //Optionally set the look and feel.
    private static boolean useSystemLookAndFeel = false;

    public TreeDemo() {
        super(new BorderLayout());

        //Create the nodes.
        DefaultMutableTreeNode top
                = new DefaultMutableTreeNode("The Java Series");
        createNodes(top);

        //Create a tree that allows one selection at a time.
        tree = new JTree();
        tree.setModel(new DefaultTreeModel(top));
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

        if (playWithLineStyle) {
            System.out.println("line style = " + lineStyle);
            tree.putClientProperty("JTree.lineStyle", lineStyle);
        }

        //Create the scroll pane and add the tree to it. 
        JScrollPane treeView = new JScrollPane(tree);

        add(treeView);

        JButton change = new JButton("Change");
        change.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();

                if (node == null) {
                    return;
                }

                Object nodeInfo = node.getUserObject();
                if (node.isLeaf()) {
                    BookInfo book = (BookInfo) nodeInfo;
                    book.bookName = "New Name";
                    ((DefaultTreeModel)tree.getModel()).nodeChanged(node);
                }
                if (DEBUG) {
                    System.out.println(nodeInfo.toString());
                }
            }
        });
        add(change, BorderLayout.SOUTH);
    }

    private class BookInfo {

        public String bookName;

        public BookInfo(String book) {
            bookName = book;
        }

        public String toString() {
            return bookName;
        }
    }

    private void createNodes(DefaultMutableTreeNode top) {
        DefaultMutableTreeNode category = null;
        DefaultMutableTreeNode book = null;

        category = new DefaultMutableTreeNode("Books for Java Programmers");
        top.add(category);

        //original Tutorial
        book = new DefaultMutableTreeNode(new BookInfo("The Java Tutorial: A Short Course on the Basics"));
        category.add(book);

        //Tutorial Continued
        book = new DefaultMutableTreeNode(new BookInfo("The Java Tutorial Continued: The Rest of the JDK"));
        category.add(book);

        //JFC Swing Tutorial
        book = new DefaultMutableTreeNode(new BookInfo("The JFC Swing Tutorial: A Guide to Constructing GUIs"));
        category.add(book);

        //Bloch
        book = new DefaultMutableTreeNode(new BookInfo("Effective Java Programming Language Guide"));
        category.add(book);

        //Arnold/Gosling
        book = new DefaultMutableTreeNode(new BookInfo("The Java Programming Language"));
        category.add(book);

        //Chan
        book = new DefaultMutableTreeNode(new BookInfo("The Java Developers Almanac"));
        category.add(book);

        category = new DefaultMutableTreeNode("Books for Java Implementers");
        top.add(category);

        //VM
        book = new DefaultMutableTreeNode(new BookInfo("The Java Virtual Machine Specification"));
        category.add(book);

        //Language Spec
        book = new DefaultMutableTreeNode(new BookInfo("The Java Language Specification"));
        category.add(book);
    }

    /**
     * Create the GUI and show it. For thread safety, this method should be
     * invoked from the event dispatch thread.
     */
    private static void createAndShowGUI() {
        if (useSystemLookAndFeel) {
            try {
                UIManager.setLookAndFeel(
                        UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                System.err.println("Couldn't use system look and feel.");
            }
        }

        //Create and set up the window.
        JFrame frame = new JFrame("TreeDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Add content to the window.
        frame.add(new TreeDemo());

        //Display the window.
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}