Solved

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

Posted on 2008-10-27
4
1,753 Views
Last Modified: 2013-11-23
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

0
Comment
Question by:Sreejith22
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 37

Accepted Solution

by:
zzynx earned 500 total points
ID: 22865290
>> 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
 

Author Comment

by:Sreejith22
ID: 22865313
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
 

Author Closing Comment

by:Sreejith22
ID: 31510424
Though I solved it on my own, thanks for your helping attitude.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 22865611
Thanx
0

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
hibernate insert example 13 39
How to convert from xls to xlsx using java 7 95
jsp error 6 46
junit example issue 2 28
In this post we will learn different types of Android Layout and some basics of an Android App.
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question