I would like to transform XML-document to java-tree-structure, but I do not know what is a java-tree-structure? For example, JTree or another? is it exists any library?
You could use an XML DOM tree expressed in Java. An XML parser will give it to you straight away.
If your XML conforms to a specific schema (and you have an XSD file for it), you can use JAXB to convert the XSD into a bunch of Java classes for conveniently manipulating the data.
You can populate a JTree with the SAXTreeBuilder construct in import org.xml.sax. Something like (NOTE: I didn't write the code below)
/*
Java, XML, and Web Services Bible
Mike Jasnowski
ISBN: 0-7645-4847-6
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Event.*;
import java.io.*;
import javax.swing.tree.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import org.apache.xerces.parsers.*;
public class XMLTreeView {
private SAXTreeBuilder saxTree = null;
private static String file = "";
public static void main(String args[]){
JFrame frame = new JFrame("XMLTreeView: [ games.xml ]");
frame.setSize(400,400);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ev){
System.exit(0);
}
});
file = "games.xml";
new XMLTreeView(frame);
}
public XMLTreeView(JFrame frame){
frame.getContentPane().setLayout(new BorderLayout());
DefaultMutableTreeNode top = new DefaultMutableTreeNode(file);
// DefaultMutableTreeNode top = new DefaultMutableTreeNode("XML Document");
saxTree = new SAXTreeBuilder(top);
try {
SAXParser saxParser = new SAXParser();
saxParser.setContentHandler(saxTree);
saxParser.parse(new InputSource(new FileInputStream(file)));
}catch(Exception ex){
top.add(new DefaultMutableTreeNode(ex.getMessage()));
}
JTree tree = new JTree(saxTree.getTree());
JScrollPane scrollPane = new JScrollPane(tree);
frame.getContentPane().add("Center",scrollPane);
frame.setVisible(true);
}
}
class SAXTreeBuilder extends DefaultHandler{
private DefaultMutableTreeNode currentNode = null;
private DefaultMutableTreeNode previousNode = null;
private DefaultMutableTreeNode rootNode = null;
public SAXTreeBuilder(DefaultMutableTreeNode root){
rootNode = root;
}
public void startDocument(){
currentNode = rootNode;
}
public void endDocument(){
}
public void characters(char[] data,int start,int end){
String str = new String(data,start,end);
if (!str.equals("") && Character.isLetter(str.charAt(0)))
currentNode.add(new DefaultMutableTreeNode(str));
}
public void startElement(String uri,String qName,String lName,Attributes atts){
previousNode = currentNode;
currentNode = new DefaultMutableTreeNode(lName);
// Add attributes as child nodes //
attachAttributeList(currentNode,atts);
previousNode.add(currentNode);
}
public void endElement(String uri,String qName,String lName){
if (currentNode.getUserObject().equals(lName))
currentNode = (DefaultMutableTreeNode)currentNode.getParent();
}
public DefaultMutableTreeNode getTree(){
return rootNode;
}
private void attachAttributeList(DefaultMutableTreeNode node,Attributes atts){
for (int i=0;i<atts.getLength();i++){
String name = atts.getLocalName(i);
String value = atts.getValue(name);
node.add(new DefaultMutableTreeNode(name + " = " + value));
}
}
}
Related
I have been using JTree to get the multiple root directories of the system, using the example FileTreeModel.java to achieve it. And also trying to get the selected leaf (path) but it throws cast error, please give me some directions on this, have posted the code so far have tried. Thanks.
import java.io.File;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.io.File;
public class FileTreeDemo {
public static void main(String[] args) {
// Figure out where in the filesystem to start displaying
File root;
if (args.length > 0) {
root = new File(args[0]);
//System.out.println(args.length);
}
else root = new File(System.getProperty("user.home"));
//System.out.println(args.length);
// Create a TreeModel object to represent our tree of files
FileTreeModel model = new FileTreeModel(root);
// Create a JTree and tell it to display our model
JTree tree = new JTree();
tree.setModel(model);
tree.setRootVisible(true);
tree.setShowsRootHandles(true);
//tree.setShowsRootHandles(true);
// The JTree can get big, so allow it to scroll.
JScrollPane scrollpane = new JScrollPane(tree);
// Display it all in a window and make the window appear
JFrame frame = new JFrame("FileTreeDemo");
frame.getContentPane().add(scrollpane, "Center");
frame.setSize(400,600);
frame.setVisible(true);
// Add a listener
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) e
.getPath().getLastPathComponent();
System.out.println("You selected " + node);
}
});
}
}
class FileTreeModel implements TreeModel {
protected File root;
public FileTreeModel(File root) { this.root = root; }
public Object getRoot() { return root; }
public boolean isLeaf(Object node) { return ((File)node).isFile(); }
public int getChildCount(Object parent) {
String[] children = ((File)parent).list();
if (children == null) return 0;
return children.length;
}
public Object getChild(Object parent, int index) {
String[] children = ((File)parent).list();
if ((children == null) || (index >= children.length)) return null;
return new File((File) parent, children[index]);
}
public int getIndexOfChild(Object parent, Object child) {
String[] children = ((File)parent).list();
if (children == null) return -1;
String childname = ((File)child).getName();
for(int i = 0; i < children.length; i++) {
if (childname.equals(children[i])) return i;
}
return -1;
}
public void valueForPathChanged(TreePath path, Object newvalue) {}
public void addTreeModelListener(TreeModelListener l) {}
public void removeTreeModelListener(TreeModelListener l) {}
}
In your model you store File's instead of DefaultMutableTreeNode, because of you get ClassCastException here:
DefaultMutableTreeNode node = (DefaultMutableTreeNode)e.getPath().getLastPathComponent();
Change your listener like next:
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
File node = (File) e.getPath().getLastPathComponent();
System.out.println("You selected " + node);
}
});
Here is the run down on my program
Lists all folders, subfolders, and files of X extension from a specified directory. You can view, edit, copy, etc the contents of the files. Each file has a .dat file associated with it that contains information such as keywords and last use date.
Right now I'm creating a filter. The way it should filter is take the inputted text and return any folders and files with the filter in its name, files which keywords contain and files which contents contain.
Easy enough, right?
My only problem is that it will do one of the following (based on location of File)
if folder matches
-> only lists to that folder, but not contents
if file matches
-> only lists file if its in JTree root
if file matches but is in a folder which doesnt match
-> doesnt display
I apologize if that is hard to understand. Below is functional code, copied and cleaned up from my real program. Uses apache commons 2.4
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.io.File;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.border.LineBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;
import org.apache.commons.io.FileUtils;
public class NGui {
JFrame frame;
private JTree tree;
private JTextField jtf;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager
.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
new NGui();
}
});
}
public NGui() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.getContentPane().setLayout(null);
frame.setSize(250, 400);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 50, 200, 300);
frame.getContentPane().add(scrollPane);
tree = new JTree(addNodes(new File(getWorkPath())));
tree.setRootVisible(true);
tree.setShowsRootHandles(true);
tree.setBorder(new LineBorder(new Color(0, 0, 0)));
tree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION);
scrollPane.setViewportView(tree);
tree.getSelectionModel().addTreeSelectionListener(
new TreeSelectionListener() {
#Override
public void valueChanged(TreeSelectionEvent e) {
treeValueChanged(e);
}
});
tree.setCellRenderer(new FileTreeCellRenderer());
jtf = new JTextField();
jtf.setBorder(new LineBorder(new Color(0, 0, 0)));
jtf.setBounds(10, 10, 150, 25);
Object actionKey = jtf.getInputMap(JComponent.WHEN_FOCUSED).get(
KeyStroke.getKeyStroke("ENTER"));
jtf.getActionMap().put(actionKey, new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent ae) {
try {
filterResults(ae);
} catch (Exception e) {
e.printStackTrace();
}
}
});
frame.getContentPane().add(jtf);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void treeValueChanged(TreeSelectionEvent e) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree
.getLastSelectedPathComponent();
log("Selected Node: " + node);
}
private void log(Object o) {
System.out.println(o);
}
private String getWorkPath() {
return ".";
}
public void filterResults(ActionEvent ae) throws Exception {
final String str = jtf.getText();
reloadTree("."); // refreshes from any previous searches
DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel()
.getRoot();
reloadTree(root.toString(), str);
}
public DefaultMutableTreeNode addNodes(File dir, String filter)
throws Exception {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(dir);
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
if (file.getPath().contains(filter)) {
log("adding: " + file.toString());
node.add(addNodes(file));
}
} else {
// apache commons 2.4
String tmpContent = FileUtils.readFileToString(file);
if (file.getPath().contains(filter)
|| tmpContent.contains(filter)) {
log("adding: " + file.toString());
node.add(new DefaultMutableTreeNode(file));
}
}
}
return node;
}
public DefaultMutableTreeNode addNodes(File dir) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(dir);
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
node.add(addNodes(file));
} else {
node.add(new DefaultMutableTreeNode(file));
}
}
return node;
}
public void reloadTree(final String path) {
DefaultMutableTreeNode dn = addNodes(new File(path));
tree.setModel(new DefaultTreeModel(dn));
}
public void reloadTree(final String path, final String filter)
throws Exception {
DefaultMutableTreeNode dn = addNodes(new File(path), filter);
tree.setModel(new DefaultTreeModel(dn));
}
public class FileTreeCellRenderer extends DefaultTreeCellRenderer {
private static final long serialVersionUID = 1L;
#Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
if (value instanceof DefaultMutableTreeNode) {
value = ((DefaultMutableTreeNode) value).getUserObject();
if (value instanceof File) {
value = ((File) value).getName();
}
}
return super.getTreeCellRendererComponent(tree, value, sel,
expanded, leaf, row, hasFocus);
}
}
}
The problem lies in the filtering algorithm.
You missed out to call the filter on the subcomponents again (instead of addNodes(file) you have to call addNodes(file, filter)).
Directory nodes where only added if they match, not if subcomponents match.
A quick hack to make your code working looks like this (replace the addNodes method):
public DefaultMutableTreeNode addNodes(File dir, String filter)
throws Exception {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(dir);
//true iff any subcomponent matches
boolean matchFound = false;
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
if (file.getName().contains(filter)) {
matchFound = true;
}
//always call addNodes on directories, because subcomponents may match
//null return value indicates no match (with Java 8 use Optional for this)
DefaultMutableTreeNode maybeNode = addNodes(file, filter);
if(maybeNode != null) {
matchFound = true;
node.add(maybeNode);
}
} else {
// apache commons 2.4
String tmpContent = FileUtils.readFileToString(file);
if (file.getName().contains(filter)
|| tmpContent.contains(filter)) {
matchFound = true;
log("adding file: " + file.toString());
node.add(new DefaultMutableTreeNode(file));
}
}
}
//only return node if node itself or subcomponent matches
if(matchFound || dir.getName().contains(filter)) {
return node;
}
//return null otherwise
return null;
}
I am currently stuck at reading a directory into an ArrayList or better an Array in Java.
I want to use the Data in a JTree.
That's the code I currently use:
//After the definiton of the Class
private ArrayList<File> files = new ArrayList<File>();
// In the main method
this.parse(new File("."));
DefaultMutableTreeNode root = processHierarchy(files.toArray());
this.tree = new JTree(root);
private void parse(File parent)
{
files.add(parent);
if(parent.isDirectory())
{
System.out.println("DIR: "+parent.getName());
String[] child = parent.list();
if(child != null)
{
for(int i = 0; i < child.length; i++)
{
File f = new File(parent, child[i]);
this.parse(f);
}
}
}
else
{
System.out.println("FILE: "+parent.getName());
}
}
Anyone got an idea?
I found this code online that searches a path and then displays it in a JTree.
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.io.*;
public class SimpleTree extends JPanel {
JTree tree;
DefaultMutableTreeNode root;
public SimpleTree() {
root = new DefaultMutableTreeNode("root", true);
getList(root, new File("C:\\Program Files")); // change path here
setLayout(new BorderLayout());
tree = new JTree(root);
tree.setRootVisible(false);
add(new JScrollPane((JTree)tree),"Center");
}
public Dimension getPreferredSize(){
return new Dimension(200, 120);
}
public void getList(DefaultMutableTreeNode node, File f) {
if(!f.isDirectory()) {
// We keep only JAVA source file for display in this HowTo
if (f.getName().endsWith("java")) {
System.out.println("FILE - " + f.getName());
DefaultMutableTreeNode child = new DefaultMutableTreeNode(f);
node.add(child);
}
}
else {
System.out.println("DIRECTORY - " + f.getName());
DefaultMutableTreeNode child = new DefaultMutableTreeNode(f);
node.add(child);
File fList[] = f.listFiles();
for(int i = 0; i < fList.length; i++)
getList(child, fList[i]);
}
}
public static void main(String s[]){
MyJFrame frame = new MyJFrame("Directory explorer");
}
}
class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent e) {
Window win = e.getWindow();
win.setVisible(false);
System.exit(0);
}
}
class MyJFrame extends JFrame {
JButton b1, b2, b3;
SimpleTree panel;
MyJFrame(String s) {
super(s);
panel = new SimpleTree();
getContentPane().add(panel,"Center");
setSize(300,300);
setVisible(true);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowCloser());
}
}
Source: http://www.rgagnon.com/javadetails/java-0324.html
I have a custom JTree and a custom JModel; I would for the JTree to "auto-expand" when I give it a new model. At the moment, it simply collapse all the nodes to the root.
Here is an example:
private class CustomTree extends JTree {
#Override
public boolean isExpanded(TreePath path) {
return ((Person) path.getLastPathComponent).hasChildren();
}
private class CustomTreeModel extends TreeModel {
// ... omitting various implementation details
#Override
public boolean isLeaf(Object object) {
return !((Person) object).hasChildren();
}
}
Model model = new Model();
Person bob = new Person();
Person alice = new Person();
bob.addChild(alice);
model.setRoot(bob);
JTree tree = new CustomTree(new CustomTreeModel(model));
At this point, the tree correctly displays:
- BOB
- ALICE
where Alice is a child of Bob (both in the data and in the visual tree)
However, if I call:
tree.setModel(new CustomTreeModel(model));
everything is collapsed:
+ BOB
Is there a way to "auto-expand" everything in the tree when setting a new model?
The following worked for me (called after setting the new model):
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
I had a similar problem.
Your solution (as posted https://stackoverflow.com/a/15211697/837530) seemed to work for me only for the top level tree nodes.
But I needed to expand all the a descendants node. So I solved it with the following recursive method:
private void expandAllNodes(JTree tree, int startingIndex, int rowCount){
for(int i=startingIndex;i<rowCount;++i){
tree.expandRow(i);
}
if(tree.getRowCount()!=rowCount){
expandAllNodes(tree, rowCount, tree.getRowCount());
}
}
which is invoked with
expandAllNodes(tree, 0, tree.getRowCount());
where, tree is a JTree.
Unless someone has a better solution.
There's also this non-recursive version.
private void expandAllNodes(JTree tree) {
int j = tree.getRowCount();
int i = 0;
while(i < j) {
tree.expandRow(i);
i += 1;
j = tree.getRowCount();
}
}
this worked for me..
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeNode;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Enumeration;
public class JTreeNodeAutoExpandCollapse extends JFrame {
public JTreeNodeAutoExpandCollapse() throws HeadlessException {
initializeUI();
}
private void initializeUI() {
setSize(200, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode chapter1 = new DefaultMutableTreeNode("Chapter 1");
DefaultMutableTreeNode sub1 = new DefaultMutableTreeNode("1.1");
DefaultMutableTreeNode sub2 = new DefaultMutableTreeNode("1.2");
DefaultMutableTreeNode sub3 = new DefaultMutableTreeNode("1.3");
DefaultMutableTreeNode sub31 = new DefaultMutableTreeNode("1.3.1");
DefaultMutableTreeNode sub32 = new DefaultMutableTreeNode("1.3.2");
root.add(chapter1);
chapter1.add(sub1);
chapter1.add(sub2);
chapter1.add(sub3);
sub3.add(sub31);
sub3.add(sub32);
final JTree tree = new JTree(root);
expandTree(tree, false);
JScrollPane pane = new JScrollPane(tree);
pane.setPreferredSize(new Dimension(200, 200));
JPanel buttonPanel = new JPanel(new BorderLayout());
JButton expandAll = new JButton("Expand All");
expandAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
expandTree(tree, true);
}
});
JButton collapseAll = new JButton("Collapse All");
collapseAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
expandTree(tree, false);
}
});
buttonPanel.add(expandAll, BorderLayout.WEST);
buttonPanel.add(collapseAll, BorderLayout.EAST);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(pane, BorderLayout.CENTER);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
}
private void expandTree(JTree tree, boolean expand) {
TreeNode root = (TreeNode) tree.getModel().getRoot();
expandAll(tree, new TreePath(root), expand);
}
private void expandAll(JTree tree, TreePath path, boolean expand) {
TreeNode node = (TreeNode) path.getLastPathComponent();
if (node.getChildCount() >= 0) {
Enumeration enumeration = node.children();
while (enumeration.hasMoreElements()) {
TreeNode n = (TreeNode) enumeration.nextElement();
TreePath p = path.pathByAddingChild(n);
expandAll(tree, p, expand);
}
}
if (expand) {
tree.expandPath(path);
} else {
tree.collapsePath(path);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new JTreeNodeAutoExpandCollapse().setVisible(true);
}
});
}
}
public void expandTree(){
int row = 1;
while (row++ < tree.getRowCount()){
tree.expandRow(row);
}
public void collapseTree(){
int row = tree.getRowCount() - 1;
while (row-- > 0){
tree.collapseRow(row);
}
}
i want to build a tree in java. operations such as insert delete update. how to go about it? I dont want a binary tree, i want to add children based on user input
i have implemented the following
import java.util.ArrayList;
public class Tree {
private Node root;
public Tree(String rootData)
{
root=new Node();
root.data=rootData;
root.children=new ArrayList<Node>();
}
public void addChild(String name)
{
}
}
import java.util.*;
class Node {
String data;
Node parent;
List<Node> children;
public Node()
{
data=null;
children=null;
parent=null;
}
public Node(String name)
{
Node n=new Node(name);
n.data=name;
n.children=new ArrayList<Node>();
}
}
Not entirely sure what you want. You might want to look into the DefaultTreeModel implementation or the TreeModel interface for the JTree, perhaps. No need to reinvent the wheel. More often than not the wheel will look distinctly triangular.
Anyway, this might help a bit:
import java.util.ArrayList;
public class Tree {
private Node root;
public Tree(String rootData)
{
root=new Node();
root.data=rootData;
root.children=new ArrayList<Node>();
}
public List<Node> getPathToNode(Node node) {
Node currentNode = node;
List<Node> reversePath = new ArrayList<Node>();
reversePath.add(node);
while (!(this.root.equals(currentNode)) {
currentNode = currentNode.getParentNode();
reversePath.add(currentNode);
}
Collections.reverse(reversePath); // now the list is root -> node
return reversePath;
}
}
import java.util.*;
class Node {
String data;
Node parent;
List<Node> children;
/* I would remove this constructor or at least initialize the field to non-null defaults. This is bloody dangerous. */
public Node()
{
data=null;
children=null;
parent=null;
}
public Node(String name)
{
Node n=new Node(name);
n.data=name;
n.children=new ArrayList<Node>();
}
public void addChild(String name) {
this.addChild(new Node(name));
}
public void addChild(Node child) {
this.children.add(child);
}
public void removeChild(Node child) {
this.children.remove(child);
}
public void removeChild(String name) {
this.removeChild(this.getChild(name));
}
public Node getChild(int childIndex) {
return this.children.get(childIndex);
}
public Node getChild(String childName) {
for (Node child : this.children) {
if (child.getName().equals(childName)) { return child; }
}
return null;
}
public Node getParentNode() {
return this.parent;
}
}
Here is the solution
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
public class MyTree extends JFrame{
private JTree tree;
private DefaultTreeModel model;
private DefaultMutableTreeNode rootNode;
public MyTree()
{
DefaultMutableTreeNode philosophersNode = getTree();
model = new DefaultTreeModel(philosophersNode);
tree = new JTree(model);
JButton addButton = new JButton("Add ");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
addNode();
}
});
JButton removeButton = new JButton("Delete");
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
removeSelectedNode();
}
});
JPanel inputPanel = new JPanel();
inputPanel.add(addButton);
inputPanel.add(removeButton);
Container container = getContentPane();
container.add(new JScrollPane(tree), BorderLayout.CENTER);
container.add(inputPanel, BorderLayout.NORTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 500);
setVisible(true);
}
private DefaultMutableTreeNode getSelectedNode() {
return (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
}
private DefaultMutableTreeNode getTree() {
rootNode = new DefaultMutableTreeNode("Root");
return rootNode;
}
private void removeSelectedNode() {
DefaultMutableTreeNode selectedNode = getSelectedNode();
if (selectedNode != null){
if(selectedNode.toString()=="Root")
{
JOptionPane.showMessageDialog(MyTree.this, "Cannot delete root element", "Error",
JOptionPane.ERROR_MESSAGE);
}else{
model.removeNodeFromParent(selectedNode);
}
}
}
private void addNode() {
DefaultMutableTreeNode parent = getSelectedNode();
if (parent == null) {
JOptionPane.showMessageDialog(MyTree.this, "Select an area.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
String name = JOptionPane.showInputDialog(MyTree.this, "Enter Name:");
model.insertNodeInto(new DefaultMutableTreeNode(name), parent, parent.getChildCount());
}
public static void main(String args[]) {
new MyTree();
}
}