Example usage for javax.swing JTree JTree

List of usage examples for javax.swing JTree JTree

Introduction

In this page you can find the example usage for javax.swing JTree JTree.

Prototype

@ConstructorProperties({ "model" })
public JTree(TreeModel newModel) 

Source Link

Document

Returns an instance of JTree which displays the root node -- the tree is created using the specified data model.

Usage

From source file:TreeNodeVector.java

public static void main(String args[]) {
    JFrame frame = new JFrame("Book Tree");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Employee javaBooks[] = { new Employee("A", "F", 9.99f), new Employee("B", "E", 4.99f),
            new Employee("C", "D", 9.95f) };
    Employee netBooks[] = { new Employee("AA", "CC", 9.99f), new Employee("BB", "DD", 9.99f) };
    Vector<Employee> javaVector = new TreeNodeVector<Employee>("A", javaBooks);
    Vector<Employee> netVector = new TreeNodeVector<Employee>("As", netBooks);
    Object rootNodes[] = { javaVector, netVector };
    Vector<Object> rootVector = new TreeNodeVector<Object>("Root", rootNodes);
    JTree tree = new JTree(rootVector);
    TreeCellRenderer renderer = new EmployeeCellRenderer();
    tree.setCellRenderer(renderer);/*  w  ww. j  a v  a 2  s  .c  o  m*/
    JScrollPane scrollPane = new JScrollPane(tree);
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 300);
    frame.setVisible(true);
}

From source file:SimpleClient.java

public static void main(String argv[]) {
    boolean usage = false;

    for (int optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-L")) {
            url.addElement(argv[++optind]);
        } else if (argv[optind].startsWith("-")) {
            usage = true;//from w  w w .  j a  v a2  s. c  o m
            break;
        } else {
            usage = true;
            break;
        }
    }

    if (usage || url.size() == 0) {
        System.out.println("Usage: SimpleClient -L url");
        System.out.println("   where url is protocol://username:password@hostname/");
        System.exit(1);
    }

    try {
        // Set up our Mailcap entries.  This will allow the JAF
        // to locate our viewers.
        File capfile = new File("simple.mailcap");
        if (!capfile.isFile()) {
            System.out.println("Cannot locate the \"simple.mailcap\" file.");
            System.exit(1);
        }

        CommandMap.setDefaultCommandMap(new MailcapCommandMap(new FileInputStream(capfile)));

        JFrame frame = new JFrame("Simple JavaMail Client");
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        //frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        // Get a Store object
        SimpleAuthenticator auth = new SimpleAuthenticator(frame);
        Session session = Session.getDefaultInstance(System.getProperties(), auth);
        //session.setDebug(true);

        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");

        // create a node for each store we have
        for (Enumeration e = url.elements(); e.hasMoreElements();) {
            String urlstring = (String) e.nextElement();
            URLName urln = new URLName(urlstring);
            Store store = session.getStore(urln);

            StoreTreeNode storenode = new StoreTreeNode(store);
            root.add(storenode);
        }

        DefaultTreeModel treeModel = new DefaultTreeModel(root);
        JTree tree = new JTree(treeModel);
        tree.addTreeSelectionListener(new TreePress());

        /* Put the Tree in a scroller. */
        JScrollPane sp = new JScrollPane();
        sp.setPreferredSize(new Dimension(250, 300));
        sp.getViewport().add(tree);

        /* Create a double buffered JPanel */
        JPanel sv = new JPanel(new BorderLayout());
        sv.add("Center", sp);

        fv = new FolderViewer(null);

        JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sv, fv);
        jsp.setOneTouchExpandable(true);
        mv = new MessageViewer();
        JSplitPane jsp2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, jsp, mv);
        jsp2.setOneTouchExpandable(true);

        frame.getContentPane().add(jsp2);
        frame.pack();
        frame.show();

    } catch (Exception ex) {
        System.out.println("SimpletClient caught exception");
        ex.printStackTrace();
        System.exit(1);
    }
}

From source file:DOMTreeWalkerTreeModel.java

/**
 * This main() method demonstrates the use of this class, the use of the
 * Xerces DOM parser, and the creation of a DOM Level 2 TreeWalker object.
 *//*from   www. ja  va2s.c  om*/
public static void main(String[] args) throws IOException, SAXException {
    // Obtain an instance of a Xerces parser to build a DOM tree.
    // Note that we are not using the JAXP API here, so this
    // code uses Apache Xerces APIs that are not standards
    DOMParser parser = new org.apache.xerces.parsers.DOMParser();

    // Get a java.io.Reader for the input XML file and
    // wrap the input file in a SAX input source
    Reader in = new BufferedReader(new FileReader(args[0]));
    InputSource input = new org.xml.sax.InputSource(in);

    // Tell the Xerces parser to parse the input source
    parser.parse(input);

    // Ask the parser to give us our DOM Document. Once we've got the DOM
    // tree, we don't have to use the Apache Xerces APIs any more; from
    // here on, we use the standard DOM APIs
    Document document = parser.getDocument();

    // If we're using a DOM Level 2 implementation, then our Document
    // object ought to implement DocumentTraversal
    DocumentTraversal traversal = (DocumentTraversal) document;

    // For this demonstration, we create a NodeFilter that filters out
    // Text nodes containing only space; these just clutter up the tree
    NodeFilter filter = new NodeFilter() {
        public short acceptNode(Node n) {
            if (n.getNodeType() == Node.TEXT_NODE) {
                // Use trim() to strip off leading and trailing space.
                // If nothing is left, then reject the node
                if (((Text) n).getData().trim().length() == 0)
                    return NodeFilter.FILTER_REJECT;
            }
            return NodeFilter.FILTER_ACCEPT;
        }
    };

    // This set of flags says to "show" all node types except comments
    int whatToShow = NodeFilter.SHOW_ALL & ~NodeFilter.SHOW_COMMENT;

    // Create a TreeWalker using the filter and the flags
    TreeWalker walker = traversal.createTreeWalker(document, whatToShow, filter, false);

    // Instantiate a TreeModel and a JTree to display it
    JTree tree = new JTree(new DOMTreeWalkerTreeModel(walker));

    // Create a frame and a scrollpane to display the tree, and pop them up
    JFrame frame = new JFrame("DOMTreeWalkerTreeModel Demo");
    frame.getContentPane().add(new JScrollPane(tree));
    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });

    frame.setSize(500, 250);
    frame.setVisible(true);
}

From source file:Main.java

public Main() {
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("ROOT");
    DefaultTreeModel model = new DefaultTreeModel(root);
    JTree tree = new JTree(model);

    buildTreeFromString(model, "A/D/E/Node 4");
    buildTreeFromString(model, "A/C/F/Node 5");
    buildTreeFromString(model, "A/B/G/Node 6");
    buildTreeFromString(model, "A/C/H/Node 5");
    buildTreeFromString(model, "A/B/G/Node 5");

    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(tree);// w ww  .j  a v a  2 s  . com
    f.setSize(300, 300);
    f.setLocation(200, 200);
    f.setVisible(true);
}

From source file:Main.java

public Main(File dir) {
    setLayout(new BorderLayout());
    JTree tree = new JTree(addNodes(null, dir));
    tree.addTreeSelectionListener(e -> {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
        System.out.println("You selected " + node);
    });// w w w  . j  a  va 2  s. co m
    JScrollPane scrollpane = new JScrollPane();
    scrollpane.getViewport().add(tree);
    add(BorderLayout.CENTER, scrollpane);
}

From source file:Main.java

public Main(int n) {
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    Container content = getContentPane();
    JTree tree = new JTree(new OutlineNode(1, n));
    content.add(new JScrollPane(tree), BorderLayout.CENTER);
    setSize(300, 475);/*from   w  w  w .j  ava2 s.c  o  m*/
    setVisible(true);
}

From source file:Main.java

public Main() {
    DefaultMutableTreeNode contacts = new DefaultMutableTreeNode("Contacts");
    createNodes(contacts);//  w  w w.  j  av  a 2s .  c o m
    tree = new JTree(contacts);
    tree.setCellRenderer(new MyTreeCellRenderer());
    JScrollPane treeView = new JScrollPane(tree);
    add(treeView);
    setSize(400, 400);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
}

From source file:Main.java

public Main() {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTree tree = new JTree(buildDemoModel());

    JPanel buttonsPanel = new JPanel();

    JButton saveButton = new JButton("Capture state");
    saveButton.addActionListener(e -> expansionState = saveExpansionState(tree));

    JButton loadButton = new JButton("Load state");
    loadButton.addActionListener(e -> {
        loadExpansionState(tree, expansionState);
        expansionState = saveExpansionState(tree);
    });/*from www  .ja  va 2  s .c o m*/

    buttonsPanel.add(saveButton);
    buttonsPanel.add(loadButton);

    JPanel content = new JPanel(new BorderLayout());
    content.add(buttonsPanel, BorderLayout.SOUTH);
    content.add(new JScrollPane(tree), BorderLayout.CENTER);

    frame.add(content);
    frame.pack();
    frame.setVisible(true);
}

From source file:MainClass.java

public MainClass(File dir) {
    setLayout(new BorderLayout());
    JTree tree = new JTree(addNodes(null, dir));

    tree.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent e) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
            System.out.println("You selected " + node);
        }//from   w  w  w . ja  va  2 s.  c o m
    });

    JScrollPane scrollpane = new JScrollPane();
    scrollpane.getViewport().add(tree);
    add(BorderLayout.CENTER, scrollpane);
}

From source file:Main.java

public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    TreeNode root = getNodes();//  www  . ja v a  2  s  . c o  m
    DefaultTreeModel model = new DefaultTreeModel(root);
    JTree tree = new JTree(model);
    tree.setRootVisible(false);

    JButton add = new JButton("add new");
    add.addActionListener(e -> {
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (selectedNode == null) {
            return;
        }
        MyObject obj = (MyObject) selectedNode.getUserObject();
        MyObject newChild = new MyObject(obj.name + "-" + (obj.childs.size() + 1));
        obj.childs.add(newChild);
        DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(newChild);
        model.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount());
        TreeNode[] nodes = model.getPathToRoot(newNode);
        TreePath path = new TreePath(nodes);
        tree.scrollPathToVisible(path);
    });

    JButton print = new JButton("print childs");
    print.addActionListener(e -> {
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (selectedNode == null) {
            return;
        }
        MyObject obj = (MyObject) selectedNode.getUserObject();
        System.out.println(obj.childs);
    });
    JPanel btns = new JPanel();
    btns.add(add);
    btns.add(print);

    add(new JScrollPane(tree));
    add(btns, BorderLayout.SOUTH);
    pack();
    setVisible(true);
}