How to set checkboxes as checked based on the data in an XML file?

Hi,
I am trying to read an XML file and based on the data that I gather from the XML, I want to mark some of the check boxes in my GUI.

At this point, I can parse and I get the data that I want from the XML. For now, I just print it in the console. (Line 225)

The next thing that I am struggling with is to mark the check boxes in the GUI based on this data.

For example, the following is my tree in the GUI: (x represents the checkbox)

x Employee
   x John
   x Kate
   x Marry
   x Marc
   x Henry

Open in new window


And when i parse the XML, let's say I get this data:

Kate
Marc

Open in new window


What I want to do is to mark as checked only Kate and Marc in this tree.

So far, I have the following code:

The methods that are directly related with my question are:
checkItems, checkPath, readChecksFromXML, printNote

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.eclipse.swt.*;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.*;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class CheckListTree {
    private Tree tree;
    private static TreeItem item_Standards;
    private TreeItem XML_item_Standards;
    private static CheckListTree instance = null;
   
    
    private CheckListTree() {
    }
    
    public static CheckListTree getInstance()
    {
        if (instance == null) {
            instance = new CheckListTree();
        }
        //System.out.println("instance: " + instance);
        return instance;
    }
    
    
    public void unselectAll (){
        System.out.println("tree: " + tree);
        for (TreeItem item : tree.getItems()) {   
            //System.out.println("item: " + item);
            checkItems(item, false);
        }     
    }
    
    public void checkPath(TreeItem item, boolean checked, boolean grayed) {
        if (item == null) return;
        if (grayed) {
            checked = true;
        } else {
            int index = 0;
            TreeItem[] items = item.getItems();
            while (index < items.length) {
                TreeItem child = items[index];
                if (child.getGrayed() || checked != child.getChecked()) {
                    checked = grayed = true;
                    break;
                }
                index++;
            }
        }
        item.setChecked(checked);
        item.setGrayed(grayed);
        checkPath(item.getParentItem(), checked, grayed);
    }

    public void checkItems(TreeItem item, boolean checked) {
        item.setGrayed(false);
        item.setChecked(checked);
        TreeItem[] items = item.getItems();
        for (int i = 0; i < items.length; i++) {
            checkItems(items[i], checked);
        }
    }

    public void createCheckListTree(Composite compTab2, GridData layoutData, List<HashMap<Integer, String>> checkList)  {
            tree = new Tree(compTab2, SWT.BORDER | SWT.CHECK);
            tree.setLayoutData(layoutData);
            tree.addListener(SWT.Selection, new Listener() {
                public void handleEvent(Event event) {
                    if (event.detail == SWT.CHECK) {
                        TreeItem item = (TreeItem) event.item;
                        boolean checked = item.getChecked();
                        checkItems(item, checked);
                        checkPath(item.getParentItem(), checked, false);
                    }
                }
            });
                  
            
            item_Standards = new TreeItem(tree, SWT.NONE);
            item_Standards.setText("Standards");
            
            Iterator<HashMap<Integer, String>> checkListIter = checkList.iterator();
            while(checkListIter.hasNext()) {
              HashMap<Integer, String> amap =   (HashMap<Integer, String>) checkListIter .next();
              Set<?> keysetString = (Set<?>) amap .keySet();
              Iterator<?> iter = keysetString.iterator();
              while( iter.hasNext() ) {
                Integer keyVal = (Integer) iter.next();
                //System.out.println("keyVal " + keyVal);
                String valFromKey = amap.get(keyVal);
                //System.out.println("valFromKey " + valFromKey);
                TreeItem item_Substandards = new TreeItem(item_Standards, SWT.NONE);
                item_Substandards.setText(valFromKey);
              } 
            }
    } 
    
    public void write2XML(Map<Integer, TreeItem> checkListMap, Map<Integer, String> checkNameMap, String file) {
        Iterator<Entry<Integer, TreeItem>> it_checkListMap = checkListMap.entrySet().iterator();
        Iterator<Entry<Integer, String>> it_checkNameMap = checkNameMap.entrySet().iterator();
        
        try {
   
          DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
          DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
   
          // root elements
          Document doc = docBuilder.newDocument();
          Element rootElement = doc.createElement("Checks");
          doc.appendChild(rootElement);
          while (it_checkListMap.hasNext()){
              Map.Entry pairs_checkListMap = (Map.Entry)it_checkListMap.next();
              // staff elements
              Element checkList = doc.createElement("CheckList");
              
              //set attribute to CheckListType element
              Attr attr = doc.createAttribute("type");
              attr.setValue(((TreeItem) pairs_checkListMap.getValue()).getText());   
              //attr.setValue("company-wide");
              checkList.setAttributeNode(attr);
              rootElement.appendChild(checkList);
              
              //for (int i=1; i<4; i++){
              while(it_checkNameMap.hasNext()){
                  Map.Entry pairs_checkNameMap = (Map.Entry)it_checkNameMap.next();
                  // firstname elements
                  Element CheckName = doc.createElement("CheckName");
                  CheckName.appendChild(doc.createTextNode((pairs_checkNameMap.getValue()).toString()));    
                  checkList.appendChild(CheckName);
              }
          }
          // write the content into xml file 
          Transformer transformerFactory = TransformerFactory.newInstance().newTransformer();
          transformerFactory.setOutputProperty(OutputKeys.INDENT, "yes");
          transformerFactory.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
          DOMSource source = new DOMSource(doc);
          StreamResult result = new StreamResult(file);
   
          transformerFactory.transform(source, result);
   
          System.out.println("File saved!");
   
        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        }
    }
    
    
    public void readChecksFromXML(String file){

        try {
            
            //File file = new File("/Users/mkyong/staff.xml");
         
            DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance()
                                     .newDocumentBuilder();
         
            Document doc = dBuilder.parse(file);
         
            //System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
         
                if (doc.hasChildNodes()) {
             
                     TreeItem[] items = printNote(doc.getChildNodes());
                    
                    // IN HERE, I NEED 2 FOR LOOPS. ONE IS FOR THE LIST OF ITEMS IN THE 
                    //ORIGINAL TREEITEM AND THE THE OTHER ONE IS FOR THE DATA THAT    
                    //GATHER FROM THE XML. IF THE ITEM IN THE ORIGINAL TREE IS IN THE DATA 
                    //THAT COMES FROM XML THEN IT SHOULD BE MARKED AS CHECKED
                    
 for (int i = 0; i < items.length; i++) {
                         checkItems(items[i], true);
                     }
                }        
            } catch (Exception e) {
            System.out.println(e.getMessage());
            }
         
          }
         
     private static TreeItem[] printNote(NodeList nodeList) {
     //    private static void printNote(NodeList nodeList) {
         //TreeItem[] items = null;
         TreeItem XML_item_Standards;
            for (int count = 0; count < nodeList.getLength(); count++) {
         
            Node tempNode = nodeList.item(count);
         
                // make sure it's element node.
                if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
                    //System.out.println("tempNode.getNodeType() =" + tempNode.getNodeType());
                    // get node name and value
                    //System.out.println("\nNode Name =" + tempNode.getNodeName() + " [OPEN]");
                    //System.out.println("Node Value =" + tempNode.getTextContent());
                    
                    if (tempNode.getNodeName().equalsIgnoreCase("CheckName")){
                       System.out.println(" MY Node Value =" + tempNode.getTextContent()); 
                       
                       // IN HERE, I NEED TO ADD THIS STRING tempNode.getTextContent() TO A        
                       // TREEITEM [ ] . BECAUSE IN LINE 192, I WILL RETURN A TREEITEM FROM 
                       //THIS METHOD AND THEN I WILL LOOP THROUGH THE ORIGINAL TREEITEM  
                       //AND THIS NEW TREEITEM TO FIND WHICH ITEMS IN THE TREEITEM MATCH. 
                       //IF THEY MATCH, THEN I WILL MARK THEM AS CHECKED
                        
                    }
             
//                    if (tempNode.hasAttributes()) {
//             
//                        // get attributes names and values
//                        NamedNodeMap nodeMap = tempNode.getAttributes();
//             
//                        for (int i = 0; i < nodeMap.getLength(); i++) {
//             
//                            Node node = nodeMap.item(i);
//                            //System.out.println("attr name : " + node.getNodeName());
//                            //System.out.println("attr value : " + node.getNodeValue());
//             
//                        }            
//                    }
             
                    if (tempNode.hasChildNodes()) {
             
                         //loop again if has child nodes
                        printNote(tempNode.getChildNodes());
             
                    }
             
                    //System.out.println("Node Name =" + tempNode.getNodeName() + " [CLOSE]");            
                }        
            }  
            return items;
       }       
    
    public void getCheckedStandards(String file){
        TreeItem[] items = tree.getSelection();
        
        final Map<Integer, TreeItem> checkListMap;
        checkListMap = new HashMap<Integer, TreeItem>();
        
        final Map<Integer, String> checkNameMap;
        checkNameMap = new HashMap<Integer, String>();
        
        for (int i = 0; i < items.length; i++) {
            checkListMap.put(i, items[i]);
            //System.out.println("itemS: " + items[0]); 
            TreeItem[] child = items[i].getItems();
            for (int index=0; index < child.length; index++) { 
                if (child[index].getChecked()) {
                    //System.out.println("item: " + index + ": " + child[index].getText()); 
                    checkNameMap.put(index, child[index].getText());
                }
            }
        }  
        //System.out.println("checkListMap: " + checkListMap); 
        //System.out.println("checkNameMap: " + checkNameMap);
        write2XML(checkListMap, checkNameMap, file);
    }
    
}

Open in new window


In line 220, I can print the data that I read from the XML successfully.

The following are the open questions:

As I mentioned in the code in line 227:

I NEED TO ADD THIS STRING tempNode.getTextContent() TO A        
TREEITEM [ ] . BECAUSE IN LINE 192, I WILL RETURN A TREEITEM FROM 
THIS METHOD AND THEN I WILL LOOP THROUGH THE ORIGINAL TREEITEM  
AND THIS NEW TREEITEM TO FIND WHICH ITEMS IN THE TREEITEM MATCH. 
IF THEY MATCH, THEN I WILL MARK THEM AS CHECKED

Open in new window


As I mentioned in line 194:

IN HERE, I NEED 2 FOR LOOPS  AS MENTIONED EARLIER. ONE IS FOR THE LIST OF ITEMS IN THE 
ORIGINAL TREEITEM AND THE THE OTHER ONE IS FOR THE DATA THAT    
GATHER FROM THE XML. IF THE ITEM IN THE ORIGINAL TREE IS IN THE DATA 
THAT COMES FROM XML THEN IT SHOULD BE MARKED AS CHECKED

Open in new window



I would appreciate if you could help me with this code?

Thanks,
TolgarAsked:
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.

krakatoaCommented:
See if you are following how to set and unset checkboxes first :

import javax.swing.*;
import java.awt.*;
import java.util.*;


class CheckBoxer extends JFrame{

public static void main(String[] args){

CheckBoxer cb = new CheckBoxer();

cb.setLayout(new GridLayout(3, 1));
 cb.add(new Checkbox("one", null, true));
 cb.add(new Checkbox("two"));
 cb.add(new Checkbox("three"));

TreeSet ts = new TreeSet();


for(int a=0;a<cb.getContentPane().getComponents().length;a++){((Checkbox)(cb.getContentPane().getComponent(a))).setState(false);}

cb.setVisible(true);

cb.setSize(new Dimension(100,150));

cb.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

for(int a=0;a<cb.getContentPane().getComponents().length;a++){
if(((Checkbox)cb.getContentPane().getComponent(a)).getLabel().equals("two")){((Checkbox)cb.getContentPane().getComponent(a)).setState(true);}
}
}


}

Open in new window


. . .  with line 29 above being the point at which your data is evaluated for  a match of course.
0
krakatoaCommented:
oops . . .  forgot to angle the code for a Treeset. So again :

import javax.swing.*;
import java.awt.*;
import java.util.*;


class CheckBoxer extends JFrame{

static TreeSet<MyCheckbox> ts;

public static void main(String[] args){

CheckBoxer cb = new CheckBoxer();

cb.setLayout(new GridLayout(3, 1));

 cb.add(new MyCheckbox("one", null, true));
 cb.add(new MyCheckbox("two"));
 cb.add(new MyCheckbox("three"));

ts = new TreeSet<MyCheckbox>();



for(int a=0;a<cb.getContentPane().getComponents().length;a++){MyCheckbox cbx = (MyCheckbox)cb.getContentPane().getComponent(a);cbx.setState(false);ts.add(cbx);}

cb.setVisible(true);

cb.setSize(new Dimension(100,150));

cb.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

Iterator<MyCheckbox> it = ts.iterator();

while(it.hasNext()){
MyCheckbox mc = (MyCheckbox)it.next();
if(mc.getLabel().equals("two")){mc.setState(true);}
}
}


static class MyCheckbox extends Checkbox implements Comparable{

	public MyCheckbox(String s,CheckboxGroup g,boolean b){
		super(s,g,b);
	}
	public MyCheckbox(String s){
		super(s);
	}

	public int compareTo(Object o){return (1);}

}

}

Open in new window

0
krakatoaCommented:
Looks like you may be talking SWT which is not in my bag, so I'd have to pull on this one, sorry.
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

TolgarAuthor Commented:
Yes, I use SWT.

Anyone else, has any ideas?
0
krakatoaCommented:
Before I go, you could check this out :

http://www.jroller.com/santhosh/entry/jtree_with_checkboxes
0
TolgarAuthor Commented:
Thanks for your efforts, but the suggestions don't help. Do you have any other suggestions?
0
krakatoaCommented:
Afraid I don't, as I don't do SWT.
0
TolgarAuthor Commented:
Does anyone else have any idea?
0
mccarlIT Business Systems Analyst / Software DeveloperCommented:
It's a bit hard to actually write any code for you as your code has many other dependencies which we don't have, BUT I should be able to get you on the right track.

In your printNode() method (that method name doesn't really make a lot of sense but anyway), rather than returning a TreeItem[] I would just return a Set<String>, ie. a set of strings that contain each name from the XML. So line 211, should be    Set<string> results = new HashSet<String>();   and then line 227 would be    results.add(tempNode.getTextContent());   and line 259 would be   return results;


And thenin your readChecksFromXML() method, at line 194 you only need the ONE loop to go through each item in the original Tree object (ie. you don't need the second loop) because you can just do something like this...
TreeItems[] items = ....; // Get you array of items from the Tree object here
Set<String> xmlStrings = printNode(doc.getChildNodes());

for (int i = 0; i < items.length; i++) {
    String itemText = items[i].getText();
    items[i].setChecked(xmlStrings.contains(itemText));
}

Open in new window

Basically, what will happen is you will iterate through each tree item and get it's "text" value (which I assume is the same value that is in the XML) and then the ".contains()" method will see if that text value is somewhere in the set of strings returned from printNode, ie. it is in the XML file, if it is it returns true otherwise false, and this value is then passed to the .setChecked() method to set/clear the check on the tree item accordingly.
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
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
Java

From novice to tech pro — start learning today.