Checkboxes as JTree nodes - How to implement the two queries given?

Hi,
I am attaching the code snippet where I have checkboxes as JTree nodes. I get perfect output with this code, but I need to have two more requirements to be fulfilled.

1) What should be done in this code such that the parent node 'No Group' is not displayed and only its children are to be displayed?
2) When I press the submit button, how can I get the names of all the children irrespective of groups, which are checked, in a collection?
Just copy paste and run this code. It is a perfectly working one and after executing the code, my requirements will be crystal clear.

Please help with these 2 requirements.
Any help in this regard will be well appreciated with points.

Sreejith
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.util.EventObject;
import java.util.Vector;
import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;
 
public class CheckBoxNodeTreeSample {
    public static void main(String args[]) {
        JFrame frame = new JFrame("CheckBox Tree");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        Vector groupVector = new Vector();
        Vector group1 = new Vector();
        group1.add("Group1");
        group1.add("child1");
        group1.add("child2");
        group1.add("child3");
        
        Vector group2 = new Vector();
        group2.add("Group2");
        group2.add("child2");
        group2.add("child4");
        group2.add("child5");
        
        
        Vector noGroup = new Vector();
        noGroup.add("No Group");
        noGroup.add("child6");
        noGroup.add("child7");
        noGroup.add("child8");
        
        groupVector.add(group1);
        groupVector.add(group2);
        groupVector.add(noGroup);
        
        
        
        
        
    	DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");
    	
        for(int i =0;i<groupVector.size();i++){
        	DefaultMutableTreeNode node = new DefaultMutableTreeNode(new CheckBoxNode(((Vector)groupVector.elementAt(i)).elementAt(0).toString(), false));
        	for(int j=1;j<((Vector)groupVector.elementAt(i)).size();j++){
        		node.add(new DefaultMutableTreeNode(new CheckBoxNode(((Vector)groupVector.elementAt(i)).elementAt(j).toString(), false)));		
        	}
        	rootNode.add(node);
        }
        
        
        JTree tree = new JTree(rootNode);
        tree.setToggleClickCount(1);
        tree.setRootVisible(false);
        tree.setShowsRootHandles(true);
        tree.putClientProperty("JTree.lineStyle", "None");
        CheckBoxNodeRenderer renderer = new CheckBoxNodeRenderer();
        tree.setCellRenderer(renderer);
        
        tree.setCellEditor(new CheckBoxNodeEditor(tree));
        tree.setEditable(true);
        
        JButton submit = new JButton("Submit");
        submit.addActionListener(new ActionListener(){                                                        
            public void actionPerformed(ActionEvent e)              
            {  if (e.getActionCommand().equals("Submit")) {
                System.out.println("Button1 has been clicked");
            } }});
            
        JScrollPane scrollPane = new JScrollPane(tree);
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
        frame.getContentPane().add(submit, BorderLayout.PAGE_END);
        frame.setSize(400, 300);
        frame.setVisible(true);
        
        tree.setModel(new DefaultTreeModel(rootNode) {
    public void valueForPathChanged(TreePath path, Object newValue) {
        Object currNode = path.getLastPathComponent();
        super.valueForPathChanged(path, newValue);
        if ((currNode != null) && (currNode instanceof DefaultMutableTreeNode)) {
            DefaultMutableTreeNode editedNode = (DefaultMutableTreeNode) currNode;
            CheckBoxNode newCBN = (CheckBoxNode) newValue;
            
            if (!editedNode.isLeaf()) {
                for (int i = 0; i < editedNode.getChildCount(); i++) {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) editedNode.getChildAt(i);
                    CheckBoxNode cbn = (CheckBoxNode) node.getUserObject();
                    cbn.setSelected(newCBN.isSelected());
                }
            }
            else{
                boolean isAllChiledSelected = true;
               for (int i = 0; i < editedNode.getParent().getChildCount(); i++) {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) editedNode.getParent().getChildAt(i);
                    CheckBoxNode cbn = (CheckBoxNode) node.getUserObject();
                    if(!cbn.isSelected()){
                        isAllChiledSelected = false;
                    }
                }
                
                if(isAllChiledSelected){
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode)editedNode.getParent();
                      CheckBoxNode cbn = (CheckBoxNode) node.getUserObject();
                    cbn.setSelected(isAllChiledSelected);
                }
            }
            
            if (!newCBN.isSelected()) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) editedNode.getParent();
                if (node.getUserObject() instanceof CheckBoxNode)
                    ((CheckBoxNode) node.getUserObject()).setSelected(false);                            
            }                                        
        }
    }
});
    }
}
 
class CheckBoxNodeRenderer implements TreeCellRenderer {
    private JCheckBox leafRenderer = new JCheckBox();
    
    private DefaultTreeCellRenderer nonLeafRenderer = new DefaultTreeCellRenderer();
    
    Color selectionBorderColor, selectionForeground, selectionBackground,
            textForeground, textBackground;
    
    protected JCheckBox getLeafRenderer() {
        return leafRenderer;
    }
    
    public CheckBoxNodeRenderer() {
        Font fontValue;
        fontValue = UIManager.getFont("Tree.font");
        if (fontValue != null) {
            leafRenderer.setFont(fontValue);
        }
        Boolean booleanValue = (Boolean) UIManager
                .get("Tree.drawsFocusBorderAroundIcon");
        leafRenderer.setFocusPainted((booleanValue != null)
        && (booleanValue.booleanValue()));
        
        selectionBorderColor = UIManager.getColor("Tree.selectionBorderColor");
        selectionForeground = UIManager.getColor("Tree.selectionForeground");
        selectionBackground = UIManager.getColor("Tree.selectionBackground");
        textForeground = UIManager.getColor("Tree.textForeground");
        textBackground = UIManager.getColor("Tree.textBackground");
    }
    
    public Component getTreeCellRendererComponent(JTree tree, Object value,
            boolean selected, boolean expanded, boolean leaf, int row,
            boolean hasFocus) {
        
        Component returnValue;
        
        String stringValue = tree.convertValueToText(value, selected,
                expanded, leaf, row, false);
        leafRenderer.setText(stringValue);
        leafRenderer.setSelected(false);
        
        leafRenderer.setEnabled(tree.isEnabled());
        
        if (selected) {
            leafRenderer.setForeground(selectionForeground);
            leafRenderer.setBackground(selectionBackground);
        } else {
            leafRenderer.setForeground(textForeground);
            leafRenderer.setBackground(textBackground);
        }
        
        if ((value != null) && (value instanceof DefaultMutableTreeNode)) {
            Object userObject = ((DefaultMutableTreeNode) value)
            .getUserObject();
            if (userObject instanceof CheckBoxNode) {
                CheckBoxNode node = (CheckBoxNode) userObject;
                leafRenderer.setText(node.getText());
                leafRenderer.setSelected(node.isSelected());
            }
        }
        returnValue = leafRenderer;
        return returnValue;
    }
}
 
class CheckBoxNodeEditor extends AbstractCellEditor implements TreeCellEditor {
    
    CheckBoxNodeRenderer renderer = new CheckBoxNodeRenderer();
    
    ChangeEvent changeEvent = null;
    
    JTree tree1;
    
    DefaultMutableTreeNode editedNode;
    
    public CheckBoxNodeEditor(JTree tree) {
        this.tree1 = tree;
    }
    
    public Object getCellEditorValue() {
        JCheckBox checkbox = renderer.getLeafRenderer();
        CheckBoxNode checkBoxNode = new CheckBoxNode(checkbox.getText(),
                checkbox.isSelected());
        return checkBoxNode;
    }
    
    public boolean isCellEditable(EventObject event) {
        boolean returnValue = false;
        if (event instanceof MouseEvent) {
            MouseEvent mouseEvent = (MouseEvent) event;
            TreePath path = tree1.getPathForLocation(mouseEvent.getX(),
                    mouseEvent.getY());
            if (path != null) {
                Object node = path.getLastPathComponent();
                if ((node != null) && (node instanceof DefaultMutableTreeNode)) {
                    editedNode = (DefaultMutableTreeNode) node;
                    Object userObject = editedNode.getUserObject();
                    Rectangle r = tree1.getPathBounds(path);
                    int x = mouseEvent.getX() - r.x;
                    int y = mouseEvent.getY() - r.y;
                    JCheckBox checkbox = renderer.getLeafRenderer();
                    checkbox.setText("");
                    returnValue = userObject instanceof CheckBoxNode && x > 0 && x < checkbox.getPreferredSize().width;
                }
            }
        }
        return returnValue;
    }
    
    public Component getTreeCellEditorComponent(final JTree tree, Object value,
            boolean selected, boolean expanded, boolean leaf, int row) {
        
        Component editor = renderer.getTreeCellRendererComponent(tree, value,
                true, expanded, leaf, row, true);
        
        ItemListener itemListener = new ItemListener() {
            public void itemStateChanged(ItemEvent itemEvent) {
                    tree.repaint();
                    fireEditingStopped();
            }
        };
        
        if (editor instanceof JCheckBox) {
            ((JCheckBox) editor).addItemListener(itemListener);
        }
        
        return editor;
    }
}
 
class CheckBoxNode {
    String text;
    
    boolean selected;
    
    public CheckBoxNode(String text, boolean selected) {
        this.text = text;
        this.selected = selected;
    }
    
    public boolean isSelected() {
        return selected;
    }
    
    public void setSelected(boolean newValue) {
        selected = newValue;
    }
    
    public String getText() {
        return text;
    }
    
    public void setText(String newValue) {
        text = newValue;
    }
    
    public String toString() {
        return getClass().getName() + "[" + text + "/" + selected + "]";
    }
}

Open in new window

Sreejith22Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

zzynxSoftware engineerCommented:
>> 1) What should be done in this code such that the parent node 'No Group' is not displayed and only its children are to be displayed?
And what parent(node) do that children then have? The root?

>> 2) When I press the submit button, how can I get the names of all the children irrespective of groups, which are checked, in a collection?
You should probably have a look @ "Visiting All the Nodes in a JTree Component": http://www.exampledepot.com/egs/javax.swing.tree/GetNodes.html
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Sreejith22Author Commented:
I solved it zzynx,

1)
>>DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");
          
        for(int i =0;i<groupVector.size();i++){
            String group = ((Vector)groupVector.elementAt(i)).elementAt(0).toString();
           
            if (!group.equals("No Group")) {
                DefaultMutableTreeNode node = new DefaultMutableTreeNode(new CheckBoxNode(((Vector)groupVector.elementAt(i)).elementAt(0).toString(), false));
                for(int j=1;j<((Vector)groupVector.elementAt(i)).size();j++){
                        node.add(new DefaultMutableTreeNode(new CheckBoxNode(((Vector)groupVector.elementAt(i)).elementAt(j).toString(), false)));            
                }
                rootNode.add(node);
            } else {
                for(int j=1;j<((Vector)groupVector.elementAt(i)).size();j++){
                    rootNode.add(new DefaultMutableTreeNode(new CheckBoxNode(((Vector)groupVector.elementAt(i)).elementAt(j).toString(), false)));            
                }
            }
           
        }

2)
>>public void actionPerformed(ActionEvent e) {  
    if (e.getActionCommand().equals("Submit")) {
        ArrayList<String> names = new ArrayList<String>();
        fillCheckedNodes(names, rootNode);
    }
}
...
...
private void fillCheckedNodes(List<String> names, DefaultMutableTreeNode node) {
    if (node.isLeaf()) {
        CheckBoxNode cbn = (CheckBoxNode) node.getUserObject();
        if (cbn.isSelected())
            names.add(cbn.getText());
    }
    else
        for (int i = 0; i < node.getChildCount(); i++)
            fillCheckedNodes(names, (DefaultMutableTreeNode) node.getChildAt(i));
}





Still, you deserve 500.
Thanks,
Sreejith
0
Sreejith22Author Commented:
Though I solved it on my own, thanks for your helping attitude.
0
zzynxSoftware engineerCommented:
Thanx
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Editors IDEs

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.