Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: JCheckBox in Jtree

  1. #1
    Member Hikaros's Avatar
    Join Date
    Sep 2013
    Posts
    42
    My Mood
    Love
    Thanks
    10
    Thanked 2 Times in 2 Posts

    Default JCheckBox in Jtree

    hi there, i've trying to make a JTree with checkbox but i seriously can't find anywhere how to do it, i already have the code in which i create the tree but i have no idea how to make the JTree to display Checkboxes. How can i do this? how can i implement it to the code? here it is what i have:

    package tests;
     
     
    import Principal.DBInfo;
     
     
    import java.sql.*;
    import java.util.Enumeration;
    import javax.swing.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;
     
    public class MenuTree {
        DBInfo dbi = new DBInfo();
     
        public MenuTree() {
            // Create the root node, I'm assuming that the delimited strings will have
            // different string value at index 0
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("Menu");
     
            // Create the tree model and add the root node to it
            DefaultTreeModel model = new DefaultTreeModel(root);
     
            // Create the tree with the new model
            JTree tree = new JTree(model);
     
            getAndSetTreeFromMenu(model);
     
            tree.expandPath(new TreePath(root));
     
            //Create the scroll pane and add the tree to it.
            JScrollPane treeView = new JScrollPane(tree);
     
            // UI
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(treeView);
            f.setSize(300, 300);
            f.setLocation(200, 200);
            f.setVisible(true);
     
     
        }
     
        /**
         * Builds a tree from a given forward slash delimited string.
         *
         * @param model The tree model
         * @param str The string to build the tree from
         */
        private void buildTreeFromString(final DefaultTreeModel model, final String str) {
            // Fetch the root node
            DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
     
            // Split the string around the delimiter
            String [] strings = str.split("/");
     
            // Create a node object to use for traversing down the tree as it 
            // is being created
            DefaultMutableTreeNode node = root;
     
            // Iterate of the string array
            for (String s: strings) {
                // Look for the index of a node at the current level that
                // has a value equal to the current string
                int index = childIndex(node, s);
     
                // Index less than 0, this is a new node not currently present on the tree
                if (index < 0) {
                    // Add the new node
                    DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(s);
                    node.insert(newChild, node.getChildCount());
                    node = newChild;
                }
                // Else, existing node, skip to the next string
                else {
                    node = (DefaultMutableTreeNode) node.getChildAt(index);
                }
            }
        }
     
        /**
         * Returns the index of a child of a given node, provided its string value.
         *
         * @param node The node to search its children
         * @param childValue The value of the child to compare with
         * @return The index
         */
        private int childIndex(final DefaultMutableTreeNode node, final String childValue) {
            Enumeration<DefaultMutableTreeNode> children = node.children();
            DefaultMutableTreeNode child = null;
            int index = -1;
     
            while (children.hasMoreElements() && index < 0) {
                child = children.nextElement();
     
                if (child.getUserObject() != null && childValue.equals(child.getUserObject())) {
                    index = node.getIndex(child);
                }
            }
     
            return index;
        }
     
        public void getAndSetTreeFromMenu(DefaultTreeModel model){
     
     
            try{
                Connection con = DriverManager.getConnection(dbi.getDB_URL(), dbi.getUSER(), dbi.getPW());
                PreparedStatement pst = con.prepareStatement("select * from menu");
                ResultSet rsMenu = pst.executeQuery();
     
                while (rsMenu.next()){
                    /*agregando menus*/
     
                    String menuAndItems = rsMenu.getString("menu") + "/";
                    String auxMenu = menuAndItems;
     
                    pst = con.prepareStatement("select * from submenu where idmenu = ?");
                    pst.setInt(1, rsMenu.getInt("idmenu"));
                    ResultSet rsSubMenu = pst.executeQuery();
     
                    /*agregando sub menus si existen*/
                    while (rsSubMenu.next()){
                        if (!rsMenu.wasNull()){
                            menuAndItems += rsSubMenu.getString("submenu") + "/";
     
     
                            pst = con.prepareStatement("select * from menuitem where idmenu = ? and idsubmenu = ?");
                            pst.setInt(1, rsMenu.getInt("idmenu"));
                            pst.setInt(2, rsSubMenu.getInt("idsubmenu"));
                            ResultSet rsMenuItem = pst.executeQuery();
     
                            /*agregando items de sub menu si existen*/
                            while (rsMenuItem.next()){
                                String aux = menuAndItems;
                                menuAndItems += rsMenuItem.getString("menuitem");
                                buildTreeFromString(model, menuAndItems);
                                menuAndItems = aux;
                            }
                        }
                    }
     
                    pst = con.prepareStatement("select * from menuitem where idmenu = ? and idsubmenu is null");
                    pst.setInt(1, rsMenu.getInt("idmenu"));
                    ResultSet rsMenuItem = pst.executeQuery();
     
                    /*agregando items a menus*/
                    while(rsMenuItem.next()){
                        menuAndItems = auxMenu;
     
                        menuAndItems += rsMenuItem.getString("menuitem");
                        buildTreeFromString(model, menuAndItems);
                    }
     
     
                }/*fin while principal*/
     
     
            }catch(SQLException e){}
        }
     
     
     
        public static void main(String[] args) {
            try {
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");}
            catch (ClassNotFoundException e) {}
            catch (InstantiationException e) {}
            catch (IllegalAccessException e) {}
            catch (UnsupportedLookAndFeelException e) {}
     
            new MenuTree();
        }
    }

    it creates the Tree based of a menu structure in a database, it works fine, however how i said before, i have no idea how to add the checkboxes, can someone help me with that please?


  2. #2
    Forum VIP
    Join Date
    Jun 2011
    Posts
    317
    My Mood
    Bored
    Thanks
    47
    Thanked 89 Times in 74 Posts
    Blog Entries
    4

    Default Re: JCheckBox in Jtree

    You will need to extend the functionality of the JTree to accomplish this by writing your own TreeCellEditor and DefaultMutableTreeNode. Some sample code here and here. Personally, I would go with an existing solution like JIDE rather than rolling out my own.

  3. #3
    Member Hikaros's Avatar
    Join Date
    Sep 2013
    Posts
    42
    My Mood
    Love
    Thanks
    10
    Thanked 2 Times in 2 Posts

    Default Re: JCheckBox in Jtree

    oooh okay, sweet, thank you. I will actually look into JIDE since it seems to be seriously useful and time saving haha i've been spending so much time with the JTree, this thing is a nightmare :/

Similar Threads

  1. JCheckBox and sql recordset
    By bczm8703 in forum JDBC & Databases
    Replies: 1
    Last Post: October 23rd, 2011, 10:30 AM
  2. How to implement JCheckBox inside JButton?
    By s1w in forum AWT / Java Swing
    Replies: 2
    Last Post: September 16th, 2011, 12:18 PM
  3. JCheckBox help is this possible?
    By derekxec in forum AWT / Java Swing
    Replies: 5
    Last Post: September 12th, 2011, 05:40 PM
  4. JTree not expanding?
    By captain alge in forum AWT / Java Swing
    Replies: 1
    Last Post: April 15th, 2011, 03:32 AM
  5. [SOLVED] Jtree help
    By sman36 in forum AWT / Java Swing
    Replies: 1
    Last Post: December 6th, 2010, 09:39 AM