How To Insert Update Delete Selected Node From JTree Using Java NetBeans
In this Java Tutorial we will see How To Add Edit Remove The Selected JTree Node Using DefaultMutableTreeNode + DefaultMutableTreeNode + TreeSelectionModel + The JTextFields Value On JTree Mouse Clicked Event To Get The Selected Node And 3 Button To Do The Insert, Update, Delete In Java Programming Language And NetBeans IDE .
Project Source Code:
private void jTree1MouseClicked(java.awt.event.MouseEvent evt) {
// Display Selected Node Text Into JTextFields
TreeSelectionModel smd = jTree1.getSelectionModel();
if(smd.getSelectionCount() > 0){
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) jTree1.getSelectionPath().getLastPathComponent();
jTextField1.setText(selectedNode.getUserObject().toString());
}
}
private void jButtonAddActionPerformed(java.awt.event.ActionEvent evt) {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) jTree1.getSelectionPath().getLastPathComponent();
DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(jTextField1.getText());
selectedNode.add(newNode);
// reload jtree model
DefaultTreeModel model = (DefaultTreeModel)jTree1.getModel();
model.reload();
}
private void jButtonEditActionPerformed(java.awt.event.ActionEvent evt) {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) jTree1.getSelectionPath().getLastPathComponent();
selectedNode.setUserObject(jTextField1.getText());
// reload jtree model
DefaultTreeModel model = (DefaultTreeModel)jTree1.getModel();
model.reload();
}
private void jButtonEdit1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) jTree1.getSelectionPath().getLastPathComponent();
if(selectedNode != jTree1.getModel().getRoot())
{
DefaultTreeModel model = (DefaultTreeModel)jTree1.getModel();
model.removeNodeFromParent(selectedNode);
model.reload();
}
}