Add, delete, and rename a complete node instance using JTree

Source: Internet
Author: User

First, let's take a look at the effect, as shown in. This directory structure tree enables adding sub-directories, deleting directories, and renaming directories by right-clicking the Pop menu, of course, you can also rename the directory node by double-clicking the directory node. Next, let's take a look at how to implement it. To put it simply, it is not too difficult to add or delete data. You can use the two basic methods of DefaultTreeModel: treeModel. insertNodeInto (childNode, parent, parent. getChildCount (); and treeModel. removeNodeFromParent (currentNode);. When adding the UserObject, make sure that the UserObject (the object put in the TreeNode) is the real user data object. The implementation of node rename can be described as a lot of twists and turns, implementing the 'how to use a tree' method in the Oralce official document, adding a TreeModel listener to the treeModel to listen for changes in the TreeNode value, however, the UserObject type obtained in it is changed to String, and the original custom object type is lost, which is very strange! Finally, the solution was found in StackoverFlow to implement a custom TreeModel and implement the valueForPathChanged method. Bytes. In addition, it is worth mentioning that you can use the following section to achieve the renaming effect by double-clicking or right-clicking the rename! Isn't it awesome? If (evt. getClickCount () = 2) {TreePath path = tree. getSelectionPath (); tree. startEditingAtPath (path);} the code in this article depends on several other classes in the above link. You can search for them in the previous article.

Package test; import java. awt. gridBagConstraints; import java. awt. gridBagLayout; import java. awt. insets; import java. awt. toolkit; import java. awt. event. actionEvent; import java. awt. event. actionListener; import java. awt. event. mouseAdapter; import java. awt. event. mouseEvent; import java. util. arrayList; import java. util. list; import javax. swing. abstractAction; import javax. swing. JButton; import javax. s Wing. JLabel; import javax. swing. JOptionPane; import javax. swing. JPanel; import javax. swing. JPopupMenu; import javax. swing. JScrollPane; import javax. swing. JTree; import javax. swing. swingUtilities; import javax. swing. event. treeModelEvent; import javax. swing. event. treeModelListener; import javax. swing. tree. defaultMutableTreeNode; import javax. swing. tree. defaultTreeModel; import javax. swing. tree. mutab LeTreeNode; import javax. swing. tree. treeNode; import javax. swing. tree. treePath; import javax. swing. tree. treeSelectionModel; import org. apache. log4j. logger; public class TreePanel extends JPanel {private final Logger logger = Logger. getLogger (TreePanel. class); private static final long serialVersionUID = 1975904153214104961l; private JTree tree; private InnerDocsMgt mainPanel; private List <VEachDi R> dirsList = new ArrayList <VEachDir> (); private defatretreemodel treeModel; private DefaultMutableTreeNode rootNode; private Toolkit toolkit = Toolkit. getdefatooltoolkit (); public TreePanel (InnerDocsMgt mainPanel) {super (); this. mainPanel = mainPanel; init ();} public void init () {GridBagLayout gbl_panel = new GridBagLayout (); gbl_panel.columnWidths = new int [] {54, 0, 0, 0, 0, 0, 0, 0, 0}; gbl_p Anel. rowHeights = new int [] {31, 0, 0}; gbl_panel.columnWeights = new double [] {1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double. MIN_VALUE}; gbl_panel.rowWeights = new double [] {0.0, 1.0, Double. MIN_VALUE}; this. setLayout (gbl_panel); JLabel lblNewLabel = new JLabel ("\ u5185 \ u90E8 \ u8D44 \ u6599 \ u76EE \ u5F55 \ u5217 \ u8868"); Response response = new response (); Idwidth = 5; gbc_lblNewLabel.insets = new Insets (0, 0, 5, 5); gbc_lblNewLabel.gridx = 0; gbc_lblNewLabel.gridy = 0; add (lblNewLabel, gbc_lblNewLabel ); JButton saveDirsOprBt = new JButton ("\ u4FDD \ u5B58 \ u76EE \ u5F55 \ u64CD \ u4F5C"); required bytes = new GridBagConstraints (); counts = new Insets (0, 0, 5, 5); gbc_saveDirsOprBt.gridx = 5; gbc_saveDirsOprBt.gridy = 0; add (saveDirsOprBt, gbc_saveDirsOprBt); saveDirsOprBt. addActionListener (new ActionListener () {@ Override public void actionreceivmed (ActionEvent e) {String title = "note! "; String message =" are you sure you want to save the changes to the directory! "; Int messageType = JOptionPane. INFORMATION_MESSAGE; int result = JOptionPane. showConfirmDialog (mainPanel, message, title, JOptionPane. YES_NO_OPTION, messageType); if (result = JOptionPane. YES_OPTION) {System. out. println ("Yes"); logger. debug ("the user has fixed the modification to the directory! "); DocsMgtRmi. getINS (). saveDirChanged (dirsList) ;}}); JScrollPane scrollPane = new JScrollPane (); gbc_scrollPane = new GridBagConstraints (); rows = 7; rows = GridBagConstraints. BOTH; gbc_scrollPane.gridx = 0; gbc_scrollPane.gridy = 1; add (scrollPane, gbc_scrollPane); VEachDir rootDir = new VEachDir (0, "/", 0,123); rootNode = new DefaultMuta BleTreeNode (rootDir); createNodes (rootNode); treeModel = new DocTreeModel (rootNode); treeModel. addTreeModelListener (new DocTreeModelListener (); tree = new JTree (treeModel); tree. getSelectionModel (). setSelectionMode (TreeSelectionModel. SINGLE_TREE_SELECTION); scrollPane. setViewportView (tree); tree. setEditable (true); tree. setDragEnabled (true); tree. setTransferHandler (new DocsTreeTransferHanlder (dir SList); setPopupMenu ();} private void createNodes (DefaultMutableTreeNode top) {List <DefaultMutableTreeNode> nodes = DocsMgtRmi. getINS (). getFirstLevelDirs (); for (DefaultMutableTreeNode one: nodes) {top. add (one) ;}} public DefaultMutableTreeNode getSelectedNode () {return (DefaultMutableTreeNode) tree. getLastSelectedPathComponent ();} public void setPopupMenu () {final JPopupMenu pop = new J PopupMenu (); pop. add (new AbstractAction ("add subdirectory") {private static final long serialVersionUID = 1L; public void actionreceivmed (ActionEvent e) {System. out. println ("Tree Add"); VEachDir newDir = new VEachDir (0, "new directories", 0,123); DefaultMutableTreeNode newNode = new DefaultMutableTreeNode (newDir ); addObject (newDir) ;}}); pop. add (new AbstractAction ("delete directory") {private static final long serialVersionU ID = 1L; public void actionreceivmed (ActionEvent e) {System. out. println ("Delete"); removeCurrentNode () ;}}); pop. add (new AbstractAction ("RENAME") {private static final long serialVersionUID = 1L; public void actionreceivmed (ActionEvent e) {TreePath path = tree. getSelectionPath (); tree. startEditingAtPath (path) ;}}); tree. addMouseListener (new MouseAdapter () {@ Override public void mouseReleased (Mo UseEvent e) {if (e. isMetaDown () {pop. show (tree, e. getX (), e. getY () ;}} public void mouseClicked (MouseEvent evt) {if (evt. getClickCount () = 1) {SwingUtilities. invokeLater (new Runnable () {public void run () {mainPanel. selectOneDir () ;}}) ;}else if (evt. getClickCount () = 2) {TreePath path = tree. getSelectionPath (); tree. startEditingAtPath (path) ;}});}/** Remove the currently selecte D node. */public void removeCurrentNode () {TreePath currentSelection = tree. getSelectionPath (); if (currentSelection! = Null) {response currentNode = (DefaultMutableTreeNode) (currentSelection. getLastPathComponent (); MutableTreeNode parent = (MutableTreeNode) (currentNode. getParent (); if (parent! = Null) {treeModel. removeNodeFromParent (currentNode); return ;}// Either there was no selection, or the root was selected. toolkit. beep ();}/** Add child to the currently selected node. */public DefaultMutableTreeNode addObject (Object child) {DefaultMutableTreeNode parentNode = null; TreePath parentPath = tree. getSelectionPath (); if (parentPath = null) {parentNode = rootNode;} else {parentNode = (DefaultMutableTreeNode) (parentPath. getLastPathComponent ();} return addObject (parentNode, child, true);} public jsonaddobject (DefaultMutableTreeNode parent, Object child) {return addObject (parent, child, false );} public jsonaddobject (DefaultMutableTreeNode parent, Object child, boolean shouldBeVisible) {DefaultMutableTreeNode childNode = new parent (child); if (parent = null) {parent = rootNode ;} // It is key to invoke this on the TreeModel, and NOT // DefaultMutableTreeNode treeModel. insertNodeInto (childNode, parent, parent. getChildCount (); // Make sure the user can see the lovely new node. if (shouldBeVisible) {tree. scrollPathToVisible (new TreePath (childNode. getPath ();} return childNode;} class DocTreeModelListener implements TreeModelListener {public void treeNodesChanged (TreeModelEvent e) {TreePath tp = e. getTreePath (); DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) (tp. getLastPathComponent ();/** If the event lists children, then the changed node is the child * of the node we 've ve already gotten. otherwise, the changed node and * the specified node are the same. */int index = e. getChildIndices () [0]; DefaultMutableTreeNode changedNode = (DefaultMutableTreeNode) (parentNode. getChildAt (index); VEachDir newdir = (VEachDir) changedNode. getUserObject (); dirsList. add (newdir);} public void treeNodesInserted (TreeModelEvent e) {} public void treeNodesRemoved (TreeModelEvent e) {} public void treeStructureChanged (TreeModelEvent e) {System. out. println ("treeStructureChanged") ;}} private class DocTreeModel extends defatretreemodel {private static final long serialVersionUID = 922481109805910953l; public DocTreeModel (TreeNode root) {super (root );} @ Override public void valueForPathChanged (TreePath path, Object newValue) {Object obj = (DefaultMutableTreeNode) path. getLastPathComponent ()). getUserObject (); (VEachDir) obj ). setDirName (newValue. toString (); super. valueForPathChanged (path, obj );}}}

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.