How to reset checkbox status to its default value after an action in JAVA?

Hi,
I have GUI and in this GUI I have some checkboxes.

When I first create the GUI the checkboxes are set checked by default.

Then the user can unselect some of the checkboxes. However, when I click at button on the UI to trigger an action these checkboxes should be set to true again.

But this does not happen. The checkboxes cannot be set to true eventhough I use the same method to set them true. I don't get any errors.

What am I doing wrong?  

Note: When I debug the code, I can clearly see that the checkboxes are set to true again but in the UI I don't see the change.

This is the code that I use to set the checkboxes to true:

    public void setAllChecked(){
        error.setSelection(true);
        System.out.println("Error Status after: " + error.getSelection());
        failed.setSelection(true);
        passed.setSelection(true);       
    }

Open in new window

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.

mccarlIT Business Systems Analyst / Software DeveloperCommented:
Is this in your Gui.java source file? Can you post the full code?
0
TolgarAuthor Commented:
In the Gui.java, the related code is this and it runs at the time of the GUI creation:

        CSFilteringCheckBoxes checkBoxes = new CSFilteringCheckBoxes(compTB3, SWT.FLAT);

Open in new window


In CSFilteringCheckBoxes.java: Line 42 below sets the checkboxes to true and it works as expected for the first time I create the UI.

public class CSFilteringCheckBoxes extends Composite {
    
    private static Shell shell;
    private static Table table;
    private static String[] titles;
    private static Display display;
    
    private Button error = new Button(this, SWT.CHECK);
    private Button failed = new Button(this, SWT.CHECK);
    private Button passed = new Button(this, SWT.CHECK);
    private Label caption = new Label(this, SWT.HORIZONTAL | SWT.CENTER);
    
    private static List<CheckDetail> checkDetails = null;
    private static List<CheckDetail> checkDetailsTable = null;

    boolean fileCreated = false;
    boolean unChecked = false;
    
    
    
    public CSFilteringCheckBoxes(Composite parent, int style) {
        super(parent, style);
        Font font = new Font(parent.getDisplay(),"Arial",9, SWT.NORMAL);
        final Color lightgray;
        lightgray = new Color (parent.getDisplay(), 140, 140, 140);
        
        GridLayout gl = new GridLayout(); gl.verticalSpacing = 4;
        setLayout(gl);
        error.setText("Error");
        failed.setText("Failed");
        passed.setText("Passed");
        caption.setText("Filtering");
        //caption.setForeground(lightgray);
        caption.setFont(font);
        
        
//        error.setSelection(true);
//        failed.setSelection(true);
//        passed.setSelection(true);

        //THIS IS WHERE I SET ALL CHECKBOXES TO TRUE
        setAllChecked();
        
        //setFilterChecks();
        
        caption.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // center the caption
        setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_GRAY));
        error.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_GRAY));
        failed.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_GRAY));
        passed.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_GRAY));
        caption.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_GRAY));
        
        
        failed.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                //String string = event.detail == SWT.CHECK ? "Checked" : "Selected";
                if (failed.getSelection()) {
                    unChecked = false;
                    //show failed checks
                    System.out.println("Failed checked");
                    try {
                        showFilteredResults("Failed");
                        List<FilterCheckStatus> filterCheckStatus_new = getFilterChecks();
                        //filterCheckStatus_new.get(0).setFailedStatus(true);
                        //failed.setSelection(true);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    try {
                        unChecked = true;
                        showFilteredResults("Failed");
                        List<FilterCheckStatus> filterCheckStatus_new = getFilterChecks();
                        //filterCheckStatus_new.get(0).setFailedStatus(false);
                        //failed.setSelection(false);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }                  
                }
            }
        });
   
    
        
        passed.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                //String string = event.detail == SWT.CHECK ? "Checked" : "Selected";
                if (getFilterChecks().get(0).getPassedStatus()) {
                    unChecked = false;
                    //show failed checks
                    System.out.println("Passed checked");
                    try {
                        showFilteredResults("Passed");
                        List<FilterCheckStatus> filterCheckStatus_new = getFilterChecks();
                        //filterCheckStatus_new.get(0).setPassedStatus(true);
                        //passed.setSelection(true);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    try {
                        unChecked = true;
                        showFilteredResults("Passed");
                        List<FilterCheckStatus> filterCheckStatus_new = getFilterChecks();
                        //filterCheckStatus_new.get(0).setPassedStatus(false);
                        //passed.setSelection(false);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } 
                }
            }
        });
        
        
        
        
        
        error.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                //String string = event.detail == SWT.CHECK ? "Checked" : "Selected";               
                if (error.getSelection()) {
                    unChecked = false;
                    //show failed checks
                    System.out.println("Error checked");
                    try {
                        showFilteredResults("Error");
                        List<FilterCheckStatus> filterCheckStatus_new = getFilterChecks();
                        //filterCheckStatus_new.get(0).setErrorStatus(true);
                        //error.setSelection(true);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    try {
                        unChecked = true;
                        showFilteredResults("Error");
                        List<FilterCheckStatus> filterCheckStatus_new = getFilterChecks();
                        //filterCheckStatus_new.get(0).setErrorStatus(false);
                        //error.setSelection(false);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } 
                }
            }
            });              
     } 
    
    public void showFilteredResults(String status) throws IOException, ClassNotFoundException{

        List<CheckDetail> checkDetails = null;
        List<CheckDetail> checkDetailsTable = null;
        String content = "";
        File f = new File("C:/Temp/mtcheck/mtcheckDetails.txt");
        if (!f.exists()){
            //List<CheckDetail> checkDetails = RunPerl.checkDetailsAll;
            checkDetails = CheckRunner.getList();
            //String tmp = checkDetails.toString();
            
            FileOutputStream fout= new FileOutputStream ("C:/Temp/mtcheck/mtcheckDetails.txt");
            ObjectOutputStream oos = new ObjectOutputStream(fout);
            oos.writeObject(checkDetails);
            fout.close();
            
            FileOutputStream foutTable= new FileOutputStream ("C:/Temp/mtcheck/mtcheckDetailsTable.txt");
            ObjectOutputStream oosTable = new ObjectOutputStream(foutTable);
            oosTable.writeObject(checkDetails);
            foutTable.close();
        }
        
        FileInputStream fin= new FileInputStream ("C:/Temp/mtcheck/mtcheckDetails.txt");
        ObjectInputStream ois = new ObjectInputStream(fin);
        checkDetails= (List<CheckDetail>)ois.readObject();
        fin.close();

        
        FileInputStream finTable= new FileInputStream ("C:/Temp/mtcheck/mtcheckDetailsTable.txt");
        ObjectInputStream oisTable = new ObjectInputStream(finTable);
        checkDetailsTable= (List<CheckDetail>)oisTable.readObject();
        finTable.close();
        
        //List<CheckDetail> checkDetailsTEST = RunPerl.checkDetailsAll;
        boolean edited = false;
        boolean newRun = false;
        //for(int i = 0; i < checkDetails.size(); i++ ){ 
        
        if (!unChecked){  //means checked
            for(Iterator<CheckDetail> i = checkDetails.iterator();i.hasNext();) {
            CheckDetail checkDetail = i.next();
            System.out.println("Detail Status:" + checkDetail.getStatus());
            
                if (!status.equalsIgnoreCase("ERROR")){
                    //if (!checkDetails.get(i).getStatus().equalsIgnoreCase(status)){
                      if (!checkDetail.getStatus().equalsIgnoreCase(status)){
                          i.remove();
                          edited = true;
                          newRun = false;
                      } else{
                          edited = true;
                          newRun = false;
                      }
                } else {
                    if (!checkDetail.getStatus().contains("n/a")){  //This is a special case for errors. It will change after I update the CLI error message format.  
                        i.remove();
                        edited= true;
                        newRun = false;
                    } else{
                        edited= true;
                        newRun = false;
                    }
                }
            }                      
            checkDetailsTable.addAll(checkDetails);
        }
        
        //checkDetailsTable = checkDetails;       
        if(unChecked){
            if (checkDetailsTable != null){
                for(Iterator<CheckDetail> i = checkDetailsTable.iterator();i.hasNext();) {
                    CheckDetail checkDetailTable = i.next();
                    System.out.println("Detail Status:" + checkDetailTable.getStatus());                  
                    //if (checkDetails.get(i).getStatus().equalsIgnoreCase(status)){
                    
                    if (!status.equalsIgnoreCase("ERROR")){
                        if (checkDetailTable.getStatus().equalsIgnoreCase(status)){
                            //checkDetails.remove(i);
                            i.remove();
                            edited= true;
                            newRun = true;
                        } else{
                            edited= true;
                            newRun = true;
                        }
                    } else {
                        if (checkDetailTable.getStatus().contains("n/a")){
                            //checkDetails.remove(i);
                            i.remove();
                            edited= true;
                            newRun = true;
                        } else{
                            edited= true;
                            newRun = true;
                        }
                    }
                }
            }
            checkDetails = checkDetailsTable;
        }
               
        //checkDetailsTable = checkDetails;
        //String tmp = checkDetailsTable.toString();        
        FileOutputStream foutTable= new FileOutputStream ("C:/Temp/mtcheck/mtcheckDetailsTable.txt");
        ObjectOutputStream oosTable = new ObjectOutputStream(foutTable);
        oosTable.writeObject(checkDetailsTable);
        foutTable.close();
        
        //get the list of failed  checks
        if (edited){
            //boolean newRun = true;
            boolean evenRow = true;
            Gui.populateResultsTable(checkDetails, shell, table, titles, newRun, evenRow);  
        }
    }
    
    
    public static void setTable(Table table, String[] titles) {
        CSFilteringCheckBoxes.table = table;
        CSFilteringCheckBoxes.titles = titles;
    }  
    
    
    public static void setShell(Shell shell, Display display) {
        CSFilteringCheckBoxes.shell = shell; 
        CSFilteringCheckBoxes.display = display;
    }
    
    public void setAllChecked(){
        error.setSelection(true);
        System.out.println("Error Status after: " + error.getSelection());
        failed.setSelection(true);
        passed.setSelection(true);       
    }
    
//    public void setFilterChecks(){
//        FilterCheckStatus filterCheckStatus = new FilterCheckStatus();
//        error.setSelection(filterCheckStatus.getErrorStatus());
//        failed.setSelection(filterCheckStatus.getFailedStatus());
//        passed.setSelection(filterCheckStatus.getPassedStatus());
//    }
    
    public List<FilterCheckStatus> getFilterChecks(){
        FilterCheckStatus filterCheckStatus = new FilterCheckStatus();
        List<FilterCheckStatus> filterCheckStatuses = new ArrayList<FilterCheckStatus>();
        
        boolean errorState = error.getSelection();
        filterCheckStatus.setErrorStatus(errorState);
        boolean failedState = failed.getSelection();
        filterCheckStatus.setFailedStatus(failedState);
        boolean passedState = passed.getSelection();
        filterCheckStatus.setPassedStatus(passedState);
        
        filterCheckStatuses.add(filterCheckStatus);
        return filterCheckStatuses;
    }
    
    public static void setTableDataInitialData() throws IOException{
        checkDetails = CheckRunner.getList();
        FileOutputStream foutTable= new FileOutputStream ("C:/Temp/mtcheck/mtcheckDetailsTable.txt");
        ObjectOutputStream oosTable = new ObjectOutputStream(foutTable);
        oosTable.writeObject(checkDetails);
        foutTable.close();        
    }
    
    public static List<CheckDetail> getTableData() throws IOException, ClassNotFoundException{
        
        FileInputStream finTable= new FileInputStream ("C:/Temp/mtcheck/mtcheckDetailsTable.txt");
        ObjectInputStream oisTable = new ObjectInputStream(finTable);
        checkDetailsTable= (List<CheckDetail>)oisTable.readObject();
        finTable.close();
        
        return checkDetailsTable;
    }
        
}

Open in new window


Up to this point, the check boxes are created as checked. And the GUI is ready to use.

Then I uncheck some of the checkboxes. And then I hit a button and this button switches the tab and runs some processes in another thread. Just before, I change the tab in the code below, I reset all checks to true again. Line 57 below is supposed to set the checkboxes to true. But it does not work as expected.

SOME CODE IN HERE
 
}else if (toolItem == Gui.item23) {  
            String content = Gui.getFileList();
            //separate the text by new line characters
            //and assign them to an array
            String fileData[] = content.split("(" + System.getProperty("line.separator") + ")+");
            boolean controllerPassed = true;
            String incorrectFile = "";
            for (int j = 0; j < fileData.length; j++){
                //do not check if the changelists exist the same way 
                //you do it for files.
                // We will check the existence of changelists in the next release
                if (fileData[j].startsWith("-c")){
                    //skip this one
                    break;
                }
                fileData[j] = fileData[j].replaceAll("-f|-d", "");
                fileData[j] = fileData[j].replaceAll("-r","");
                fileData[j] = fileData[j].replaceAll("\\s+","");
                File file = new File(fileData[j]);
                if (file.exists()){
                    //do nothing
                }else{
                    controllerPassed = false;
                    incorrectFile = incorrectFile + "\n\r" + fileData[j];
                }
                
            }
            //this is to make sure the thread is not running and also the file list does not have any problem. Because, use can switch to the next tab by 
            //clicking on the tab without using the buttons and if there is a problem in either of the tab, we should run the checks at all
            if (( thread == null || (thread.getState() == Thread.State.TERMINATED) ) && fileData.length > 0 && !fileData[0].equals("") && controllerPassed){
                //If there are no checks selected then disable the RunChecks button
                //if (CheckListTree.checkNameMap.size() > 0 ){
                Map<Integer, TreeItem> checkListMap = new HashMap<Integer, TreeItem>();
                final Map<Integer, String> checkNameMapRun = new HashMap<Integer, String>();
                Map<Integer, String> checkedList = CheckListTree.getInstance().getCheckedStandards(checkListMap, checkNameMapRun);
                if (checkedList.size() > 0){
                    table.removeAll();
                    
                    File file_mtcheckDetails = new File("C:/Temp/mtcheck/mtcheckDetails.txt");
                    file_mtcheckDetails.delete();
                    File file_mtcheckDetailsTable = new File("C:/Temp/mtcheck/mtcheckDetailsTable.txt");
                    file_mtcheckDetailsTable.delete();
                    
                    CheckRunner.cleanList();
                    //CSFilteringCheckBoxes checkBoxes= new CSFilteringCheckBoxes();
                    //checkBoxes.setAllChecked();
                    Gui.swichTabResults();
                    final String fileListContent = Gui.getFileList();
                    //Map<Integer, TreeItem> checkListMap = new HashMap<Integer, TreeItem>();
                    final Map<Integer, String> checkNameMap1= new HashMap<Integer, String>();
                    final Map<Integer, String> checkNameMap = CheckListTree.getInstance().getCheckedStandards(checkListMap, checkNameMap1);
                    final Composite compTB3_table= Gui.getCompTB3();

                    CSFilteringCheckBoxes checkBoxes= new CSFilteringCheckBoxes(compTB3_table, SWT.FLAT);
                    checkBoxes.setAllChecked();
                    
                    new Thread(new Runnable() {
                        public void run() {                          
                                try {
                                    thread = Thread.currentThread();
                                    List<CheckDetail> checkDetails = RunPerl.runMwcheck(fileListContent,checkNameMap,compTB3_table);
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } finally {
                                     Gui.reenableItem23();
                                }
                        }
                    }).start();

SOME MORE CODE

Open in new window



The mtehod that I call in Line 54 (final Composite compTB3_table= Gui.getCompTB3();) was implemented like this in Gui.java:

public class Gui {
SOME CODE IN HERE

private static Composite compTB3_new;

SOME CODE IN HERE

public static void main(String[] args) throws SQLException, ClassNotFoundException {

SOME CODE IN HERE

Composite compTB3 = new Composite(compTab3, SWT.NULL);   
setCompTB3(compTB3);

SOME CODE IN HERE

} //main ends in here
} //class end in here

    public static  void setCompTB3(Composite compTB3){       
        compTB3_new = compTB3;
    }
     
    public static Composite getCompTB3(){
        return compTB3_new;
    }

Open in new window

0
mccarlIT Business Systems Analyst / Software DeveloperCommented:
Ok, so here is the problem... In the first code snippet posted (from Gui.java) you are creating a "new CSFilteringCheckBoxes" object which in turn, in its constructor, creates the checkboxes that you see in your gui.

But then on line 56 of the snippet of ToolbarListener.java that you posted, you are creating ANOTHER "new CSFilteringCheckBoxes" object which will again create new, extra checkboxes. Now I can't be sure exactly what is happening, maybe these new ones are being displayed under the existing ones, or something else, but the old checkboxes are still there and line 57 won't be setting the selection on those old ones at all.

The fix (again not ideal but this should get you going), in your Gui.java where you create the new CSFilteringCheckBoxes object, instead of assigning it to a local variable as you are doing now, assign it to a static class variable (like all the others at the top of Gui.java) called, for example, csFilteringCheckBoxes and then instead of creating the new CSFilteringCheckBoxes in your ToolbarListener.java just change line 57 (from the snippet above) to      Gui.csFilteringCheckBoxes.setAllChecked();      this will operate on the existing checkboxes rather than creating new ones.

So what IS the ideal solution? To have a proper software design from the start with a well thought out class hierarchy/design and then implement that design using Java best practises around encapsulation, etc. Yes it can be a drag at the start but in the long run it saves a lot of the types of issues that you are facing now! :)
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
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

TolgarAuthor Commented:
Yes, this solved my problem.

At this point, how can I convert this code into a better design.

Where should I start from?

Thanks,
0
mccarlIT Business Systems Analyst / Software DeveloperCommented:
Where should I start from?
From a new project! ;)  Seriously though, I know you can't just throw away everything that you have done and start again, my comment was more around trying to get the point across that in the future with our next project, to reduce the type of issues that you are seeing, you should try and start from a good solid thought out design and then do the code. Projects where you are constantly adding the next bit and adding and adding, tend to turn out like this (trust me, I've been there!)
0
TolgarAuthor Commented:
So, is there no way of refactoring this code ?
0
mccarlIT Business Systems Analyst / Software DeveloperCommented:
There is always a way. The point is: is it worth it at this point? You would need to weigh up the amount of effort required to do that (quite a lot, I'd say) vs the benefit provided?
0
TolgarAuthor Commented:
I see
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
Java

From novice to tech pro — start learning today.