In the previous tutorial, we learn about a simple JTree. This tutorial is for adding dynamic files to JTree.
Add dynamic files to JTree :
MyFrameTreeDemo.java
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
class MyFrameTreeDemo extends JFrame implements ActionListener {
DefaultMutableTreeNode root, parent, child, node;
JTree tree;
Container container;
JButton add, remove;
JPanel buttonsPanel;
TreePath treePath;
int index;
MyFrameTreeDemo() {
super("JTree Event Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
root = new DefaultMutableTreeNode("India");
parent = new DefaultMutableTreeNode("Andhra Pradesh");
child = new DefaultMutableTreeNode("Hyderabad");
parent.add(child);
child = new DefaultMutableTreeNode("Vizag");
parent.add(child);
root.add(parent);
parent = new DefaultMutableTreeNode("Tamil Nadu");
child = new DefaultMutableTreeNode("Chennai");
parent.add(child);
root.add(parent);
tree = new JTree(root);
add = new JButton("Add");
add.addActionListener(this);
remove = new JButton("Remove");
remove.addActionListener(this);
buttonsPanel = new JPanel();
buttonsPanel.add(add);
buttonsPanel.add(remove);
container = getContentPane();
container.add(new JScrollPane(tree));
container.add(buttonsPanel, BorderLayout.SOUTH);
setSize(400, 400);
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == add) {
DefaultMutableTreeNode SelectedNode;
treePath = tree.getSelectionPath();
SelectedNode = (DefaultMutableTreeNode) treePath
.getLastPathComponent();
index = SelectedNode.getIndex(SelectedNode) + 1;
String NodeStr = JOptionPane.showInputDialog(this,
"Enter the node value", "New Tree Node",
JOptionPane.QUESTION_MESSAGE);
node = new DefaultMutableTreeNode(NodeStr);
SelectedNode.insert(node, index);
tree.updateUI();
} else if (ae.getSource() == remove) {
int val = JOptionPane.showConfirmDialog(buttonsPanel,
"Please confirm to delete ?");
if (val == 0) {
DefaultMutableTreeNode SelectedNode;
treePath = tree.getSelectionPath();
SelectedNode = (DefaultMutableTreeNode) treePath
.getLastPathComponent();
if (SelectedNode.isLeaf()) {
parent = (DefaultMutableTreeNode) SelectedNode.getParent();
parent.remove(SelectedNode);
tree.updateUI();
} else {
JOptionPane.showMessageDialog(this, "Unable to Remove");
}
}
}
}
}
class TreeDemo {
public static void main(String args[]) throws Exception {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
MyFrameTreeDemo frame = new MyFrameTreeDemo();
}
}
Output :
Add File to JTree :
After Adding File to JTree :
Delete File from JTree :
After Deleting File from JTree :
Happy Learning 🙂