How not to cause GUI to freeze while running some external commands from the GUI in JAVA?

Hi,
I have a GUI and this GUI runs some external commands on the command line. While running these command the GUI gets frozen even though I use executor to create a new thread to run these processes.

In one of the posts by mccarl, he mentioned that
if code is directly in a GUI items event handler, then it doesn't matter that you are using an executor to run the tasks in a separate thread/threads because you then do a busy wait for those tasks to complete which still holds up the thread and won't allow your GUI to be responsive.

My code is not directly in it but actually my first call is in it. How else can I do it?

Can you please help me to prevent my GUI to freeze?

The other related question with code samples are here: (The last 3 posts by me are more related with this post)

http://www.experts-exchange.com/Programming/Languages/Java/Q_28262749.html
TolgarAsked:
Who is Participating?
 
mccarlConnect With a Mentor IT Business Systems Analyst / Software DeveloperCommented:
Can you please help me to prevent my GUI to freeze?
Because in all these versions of your code, you are still waiting for all the commands to run whilst you are in the main GUI thread. Let me put this another way... You GUI won't be responsive again until the handleEvent method in ToolbarListener returns. And at the moment, it does return until all the commands have finished running.

So there are a number of ways to resolve that, what I am going to show you is probably not the most elegant but it should be the most simple to implement from the code that you already have. There are two main parts to my solution, the first is to get the code that you have (from RunPerl and anything subsequent that gets called) to run in a separate thread from the GUI thread. As I said, yes you have the tasks running in separate threads but you are still waiting for them in the GUI thread, and so there isn't much difference to just running them directly in the main GUI thread. The second part has to do with a new issue that will arise after doing the first part, and that is that you can't make updates to the GUI from a different thread to the main GUI thread.

So, on to the first part.. change the code in your ToolbarListener's handleEvent method to be like the following...
        public class ToolBarListener implements Listener {
    

       @Override
       public void handleEvent(Event event) {
        
        SOME CODE IN HERE        

        } else if (toolItem == Gui.item23) {
            Gui.swichTabResults();
            Gui.item23.setEnabled(false);
            new Thread(new Runnable() {
                public void run() {
                    try {
                        List<CheckDetail> checkDetails = RunPerl.runCheck();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally {
                         Gui.reenableItem23();
                    }
                }
            }).start();

           SOME MORE CODE IN HERE

Open in new window

This code is what makes anything that happens inside RunPerl.runCheck() to be running on a different thread. This means that handleEvent() can return straight away and therefore your GUI will be responsive. Notice also that I have included the call to Gui.item23.setEnabled(false) here, as this is the more appropriate place for that call. So you should remove the original call from your futures loop in RunPerl.java

Now on to the second part, but for this I will need you to post your FULL code for Gui.java because we will need to do two things, both involved with getting changes to the GUI to run back on the GUI's thread. We will have to change the code slightly in the Gui.populateResultsTable() method and we will have to add a new method that you might have noticed from above, the Gui.reenableItem23() method. I need you to post the full code so that I can see where it should go and to see what other variables that you have defined that will help in fixing this.


Once these two parts are complete, we can then go back to your RunPerl.runCheck() method and clean up what is going on there, because while yes it may work at the moment, it is not the most efficient way to do things.
0
 
TolgarAuthor Commented:
Hi Mccarl,
I am sending you the entire Gui.java, RunPerl.java and CheckRunner.java codes:

GUI.JAVA
public class Gui {
    
    static ToolItem item_selectFilesDirectories;
    static ToolItem item_selectChangelist;
    static ToolItem item_selectFileList;
    static ToolItem item_clearList;
    static ToolItem item_SaveFileList;
    static ToolItem item13;
    static ToolItem item23;
    static CTabFolder folder;
    static ToolItem item2;
    static ToolItem item22;
    static ToolItem item222;
    static ToolItem item3;
    static ToolItem item33;
    static ToolItem item333;
    static ToolItem item3333;
    static ToolItem item33333;
    static ToolItem item333333;
    static ToolItem item3333333;
    static ToolItem item33333333;
    static ToolItem item_selectAllChecks;
    static Text txt;
    static Label helpLabel;

    
    private static ToolBarListener toolBarListener = new ToolBarListener();
    private static RunPerl runPerl = new RunPerl();
    static RWFile rwFile = new RWFile();
    static FileTree fileTree = new FileTree();
    //static ChangeListDlg changeListDlg = new ChangeListDlg(null);
    static StringBuilder buffer; 
    //static CheckListTree checks = new CheckListTree();
    
    
    public static void swichTabChecks() {
        folder.setSelection(1);
    }
    public static void swichTabResults() {
        folder.setSelection(2);
    }
    public static void swichTabFiles() {
        folder.setSelection(0);
    } 
    public static void readTxt(String fileListFile, String fileListPath) {
        buffer = new StringBuilder();
        buffer.append(txt.getText() + rwFile.readFromFile(fileListFile, fileListPath));
        String fileList = buffer.toString();
        
        txt.setText(fileList);
    }    
    public static void writeTxt(String file) {
        String content = txt.getText();
        
        //content = content.replaceAll("Use the buttons above to select files/directories, changelists, or saved file. Or you can type a list of fully-qualified names", "");
        //content = content.replaceAll("\\*", "");
        
        //Remove all empty lines
        content = content.replaceAll("(?m)^[ \t]*\r?\n", "");
        rwFile.writeToFile(content, file);
    }    
    public static void clearTxt() {
        txt.setText("");
        //txt.setText("Use the buttons above \n********************************\r\n");
    } 
    public static void selectFilesFolders() {
        fileTree.main(null);
        buffer = new StringBuilder();
        buffer.append(txt.getText() + "\r" + fileTree.getFileFolders());
        //System.out.println("FILES:" + fileTree.getFileFolders());
        String fileList = buffer.toString();
        txt.setText(fileList);
    }  
    
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        Display display = new Display();
        final Shell shell = new Shell(display);
        shell.setLocation(300,100);
        
        toolBarListener.setShell(shell,display);                  
        shell.setText("Development Desktop Tool");
        shell.setLayout(new GridLayout());        
        
        folder = new CTabFolder(shell, SWT.TOP);
        folder.setLayoutData(new GridData(SWT.FILL, GridData.FILL, true, true, 3, 3));
        CTabItem cTabItem1 = new CTabItem(folder, SWT.NONE);
        cTabItem1.setText("Files");
        CTabItem cTabItem2 = new CTabItem(folder, SWT.NONE);
        cTabItem2.setText("Checks");
        CTabItem cTabItem3 = new CTabItem(folder, SWT.NONE);
        cTabItem3.setText("Results");
       
     // -----------here starts TAB 1 -------------------- 
        Image image_Folder = new Image(display, "folder.png");
        Image image_shape_triangle = new Image(display, "shape_triangle.png");
        Image image_document = new Image(display, "document.png");
        Image image_delete = new Image(display, "delete.png");
        Image image_floppy_disk = new Image(display, "floppy_disk.png");
        Image image_navigate_right = new Image(display, "navigate_right.png");
       
        Composite compTab1 = new Composite(folder, SWT.NULL);
        GridLayout gridLayout1 = new GridLayout(3, false);
        compTab1.setLayout(gridLayout1);
        //compTab1.setLayoutData(new GridData());
        
        Composite compTB1 = new Composite(compTab1, SWT.NULL);
        GridLayout gL1 = new GridLayout(6, false);
        gL1.marginLeft = 0; gL1.marginRight = 0; gL1.horizontalSpacing = 0;
        compTB1.setLayout(gL1);
        GridData sepGD1 = new GridData(GridData.FILL_HORIZONTAL); sepGD1.horizontalSpan = 3; 
        compTB1.setLayoutData(sepGD1);
        compTB1.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_GRAY));
        
                
        //1st group
        CustomToolbar custToolBar1 = new CustomToolbar(compTB1, SWT.FLAT, "Files");
        
        item_selectFilesDirectories = new ToolItem(custToolBar1.getToolBar(), SWT.NONE);
        item_selectFilesDirectories.setImage(image_Folder); item_selectFilesDirectories.setText("Select Files/Directories"); item_selectFilesDirectories.setToolTipText("Select the files or the directory you want to analyze");
        item_selectFilesDirectories.addListener(SWT.Selection, toolBarListener);
        
        item_selectChangelist = new ToolItem(custToolBar1.getToolBar(), SWT.PUSH);
        item_selectChangelist.setImage(image_shape_triangle); item_selectChangelist.setText("Select Changelist"); item_selectChangelist.setToolTipText("Select the files in the changelist");
        item_selectChangelist.addListener(SWT.Selection, toolBarListener);
                
        item_selectFileList = new ToolItem(custToolBar1.getToolBar(), SWT.PUSH);
        item_selectFileList.setImage(image_document); item_selectFileList.setText("Select File List"); item_selectFileList.setToolTipText("Select the file list");
        item_selectFileList.addListener(SWT.Selection, toolBarListener);
        
        item_clearList = new ToolItem(custToolBar1.getToolBar(), SWT.PUSH);
        item_clearList.setImage(image_delete); item_clearList.setText("Clear List"); item_clearList.setToolTipText("Delete the list of all files below");
        item_clearList.addListener(SWT.Selection, toolBarListener);
        
        //This is the separator
        Label verticalSepartor11 = new Label(compTB1, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor11.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor11.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
        
        //2nd group
        CustomToolbar custToolBar11 = new CustomToolbar(compTB1, SWT.FLAT, "Configuration");
        
        item_SaveFileList = new ToolItem(custToolBar11.getToolBar(), SWT.NONE);
        item_SaveFileList.setImage(image_floppy_disk); item_SaveFileList.setText("Save"); item_SaveFileList.setToolTipText("Save the list of files below to text file for future reference");
        item_SaveFileList.addListener(SWT.Selection, toolBarListener);    
        
        
        //This is the separator
        Label verticalSepartor12 = new Label(compTB1, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor12.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor12.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
       
        //3rd group
        CustomToolbar custToolBar111 = new CustomToolbar(compTB1, SWT.FLAT, "Next Actions");
        
        item13 = new ToolItem(custToolBar111.getToolBar(), SWT.NONE);
        item13.setImage(image_navigate_right); item13.setText("Specify Checks"); item13.setToolTipText("Move to the next tab to select the list of checks. This icon will be enabled once you have information in the below text box with no path issues.");
        item13.addListener(SWT.Selection, toolBarListener);
  
        //This is the separator
        Label verticalSepartor13 = new Label(compTB1, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor13.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor13.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
        
        //This is the separator between the toolbar and the text box.
        Label horSepartorTab1 = new Label(compTab1, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.HORIZONTAL);
        GridData sepGridDataTab1 = new GridData(GridData.FILL_HORIZONTAL); sepGridDataTab1.horizontalSpan = 3; 
        horSepartorTab1.setLayoutData(sepGridDataTab1);horSepartorTab1.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
               
        Composite compButtons1 = new Composite(compTab1, SWT.NULL);
        FillLayout fillLayout1 = new FillLayout();
        fillLayout1.type = SWT.HORIZONTAL;                  
        compButtons1.setLayout(fillLayout1);
       
        cTabItem1.setControl(compTab1);
        
// -----------here starts TAB 2 --------------------              
        Image image_folder_document = new Image(display, "folder_document.png");
        Image image_selection_delete_2 = new Image(display, "selection_delete_2.png");
        //Image image_selectAllChecks = new Image(display, "selectAllChecks.png");

        Composite compTab2 = new Composite(folder, SWT.NULL);
        GridLayout gridLayout2 = new GridLayout(2, false);
        compTab2.setLayout(gridLayout2);
        
        Composite compTB2 = new Composite(compTab2, SWT.NULL);
        GridLayout gL2 = new GridLayout(4, false);
        gL2.marginLeft = 0; gL2.marginRight = 0; gL2.horizontalSpacing = 0;
        compTB2.setLayout(gL2);
        GridData sepGD2 = new GridData(GridData.FILL_HORIZONTAL); sepGD2.horizontalSpan = 2; 
        compTB2.setLayoutData(sepGD2);
        compTB2.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_GRAY));
        
        
        //1st group
        CustomToolbar custToolBar2 = new CustomToolbar(compTB2, SWT.FLAT, "Configuration");  
     
        item2 = new ToolItem(custToolBar2.getToolBar(), SWT.PUSH);
        item2.setImage(image_folder_document); item2.setText("Load saved check list"); item2.setToolTipText("Load the saved list of checks if you saved from previous runs");      
        item2.addListener(SWT.Selection, toolBarListener);
        
        item22 = new ToolItem(custToolBar2.getToolBar(), SWT.PUSH);
        item22.setImage(image_selection_delete_2); item22.setText("Unselect all"); item22.setToolTipText("Unselec all checks below");
        item22.addListener(SWT.Selection, toolBarListener);
        
        item222 = new ToolItem(custToolBar2.getToolBar(), SWT.PUSH);
        item222.setImage(image_floppy_disk); item222.setText("Save selections"); item222.setToolTipText("Save the list of checks to a XML file for future reference");
        item222.addListener(SWT.Selection, toolBarListener);
        
        //This is the separator
        Label verticalSepartor21 = new Label(compTB2, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor21.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor21.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
        
            
        //2nd group
        CustomToolbar custToolBar22 = new CustomToolbar(compTB2, SWT.FLAT, "Next Actions");
                
        item23 = new ToolItem(custToolBar22.getToolBar(), SWT.PUSH);
        item23.setImage(image_navigate_right); item23.setText("Run checks"); item23.setToolTipText("Run the checks against the files you selected");
        item23.addListener(SWT.Selection, toolBarListener); 
                     
        //This is the separator
        Label verticalSepartor22 = new Label(compTB2, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor22.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor22.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
        
        //This is the separator between the toolbar and the checks tree.
        Label horSepartorTab2 = new Label(compTab2, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.HORIZONTAL);
        GridData sepGridDataTab2 = new GridData(GridData.FILL_HORIZONTAL); sepGridDataTab2.horizontalSpan = 3; 
        horSepartorTab2.setLayoutData(sepGridDataTab2);horSepartorTab2.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
               
        Composite compButtons2 = new Composite(compTab2, SWT.NULL);
        FillLayout fillLayout2 = new FillLayout();
        fillLayout2.type = SWT.HORIZONTAL;                  
        compButtons2.setLayout(fillLayout2);
       
        cTabItem2.setControl(compTab2);
     // -----------here starts TAB 3 --------------------      
        Image image_breakpoint = new Image(display, "breakpoint.png");
        Image image_redo = new Image(display, "redo.png");
        Image image_gecko = new Image(display, "gecko.png");
        Image image_navigate_left2 = new Image(display, "navigate_left2_orange.png");
        Image image_exit = new Image(display, "exit.png");
        
        Composite compTab3 = new Composite(folder, SWT.NULL);
        GridLayout gridLayout3 = new GridLayout(1, false);
        compTab3.setLayout(gridLayout3);
        
        Composite compTB3 = new Composite(compTab3, SWT.NULL);
        GridLayout gL3 = new GridLayout(10, false);
        gL3.marginLeft = 0; gL3.marginRight = 0; gL3.horizontalSpacing = 0;
        compTB3.setLayout(gL3);
        GridData sepGD3 = new GridData(GridData.FILL_HORIZONTAL); sepGD3.horizontalSpan = 5; 
        compTB3.setLayoutData(sepGD3);
        compTB3.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_GRAY));

       
        //1st group
        CustomToolbar custToolBar3 = new CustomToolbar(compTB3, SWT.FLAT, "Configuration");   
       
        item3 = new ToolItem(custToolBar3.getToolBar(), SWT.PUSH);
        item3.setImage(image_floppy_disk); item3.setText("Save"); item3.setToolTipText("Save the list of files and checks to a XML file for future reference");
        item3.addListener(SWT.Selection, toolBarListener);

        //This is the separator
        Label verticalSepartor31 = new Label(compTB3, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor31.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor31.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
        
        //2nd group
        CustomToolbar custToolBar33 = new CustomToolbar(compTB3, SWT.FLAT, "Processing");             
        
        item33 = new ToolItem(custToolBar33.getToolBar(), SWT.PUSH);
        item33.setImage(image_breakpoint); item33.setText("Stop checks"); item33.setToolTipText("Stop running the checks");
        item33.addListener(SWT.Selection, toolBarListener);
        
        item333 = new ToolItem(custToolBar33.getToolBar(), SWT.PUSH);
        item333.setImage(image_redo); item333.setText("Rerun failed"); item333.setToolTipText("Rerun failed checks");
        item333.addListener(SWT.Selection, toolBarListener);

        //This is the separator
        Label verticalSepartor32 = new Label(compTB3, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor32.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor32.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
       
        
        //3rd group       
        CSFilteringCheckBoxes checkBoxes = new CSFilteringCheckBoxes(compTB3, SWT.FLAT);
        
        //This is the separator
        Label verticalSepartor33 = new Label(compTB3, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor33.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor33.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
        
        
        //4th group
        CustomToolbar custToolBar3333 = new CustomToolbar(compTB3, SWT.FLAT, "Results");
        
        item33333 = new ToolItem(custToolBar3333.getToolBar(), SWT.PUSH);
        item33333.setImage(image_floppy_disk); item33333.setText("Save results"); item33333.setToolTipText("Save the results to HTML or XML file");
        item33333.addListener(SWT.Selection, toolBarListener);  
        
        item333333 = new ToolItem(custToolBar3333.getToolBar(), SWT.PUSH);
        item333333.setImage(image_gecko); item333333.setText("Save to geck"); item333333.setToolTipText("Save the results to a geck. Geck number will be asked when you click this button");
        item333333.addListener(SWT.Selection, toolBarListener);
      
        //This is the separator
        Label verticalSepartor34 = new Label(compTB3, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor34.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor34.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
        
               
        //5th group
        CustomToolbar custToolBar33333 = new CustomToolbar(compTB3, SWT.FLAT, "Next Actions");      
    
        item3333333 = new ToolItem(custToolBar33333.getToolBar(), SWT.PUSH);
        item3333333.setImage(image_navigate_left2); item3333333.setText("Start over"); item3333333.setToolTipText("Go back to the first tab to start over");
        item3333333.addListener(SWT.Selection, toolBarListener);
        item33333333 = new ToolItem(custToolBar33333.getToolBar(), SWT.PUSH);
        item33333333.setImage(image_exit); item33333333.setText("Quit"); item33333333.setToolTipText("Quit the tool");
        item33333333.addListener(SWT.Selection, toolBarListener);
        
        //This is the separator
        Label verticalSepartor35 = new Label(compTB3, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor35.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor35.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
        //new Label(compTB3, SWT.NONE);
                              
        
        Composite compButtons3 = new Composite(compTab3, SWT.NULL);
        FillLayout fillLayout3 = new FillLayout();
        fillLayout3.type = SWT.HORIZONTAL;                  
        compButtons3.setLayout(fillLayout3);
       
        cTabItem3.setControl(compTab3);
        //new Label(compTab3, SWT.NONE);
        //new Label(compTab3, SWT.NONE);
       

        //This is the separator between the toolbar and the results table.
        Label horSepartorTab3 = new Label(compTab3, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.HORIZONTAL);
        GridData sepGridDataTab3 = new GridData(GridData.FILL_HORIZONTAL); sepGridDataTab3.horizontalSpan = 5; 
        horSepartorTab3.setLayoutData(sepGridDataTab3);horSepartorTab3.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
        
        // -----------here ends ALL TAB MENUS -------------------- 
        
        //TAB1 CONTENT
        //This is the text box   
        GridLayout groupLayout = new GridLayout();
        Group groupText = new Group(compTab1, SWT.NONE);
        groupText.setLayout(groupLayout);
        groupText.setLayoutData(new GridData(GridData.FILL_BOTH));
        groupText.setText("File List \r (Use the buttons above to select files/directories, changelists, or saved file. Or you can type a list of fully-qualified names)");
        txt = new Text(groupText, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
        TxtFocusListener txtFL = new TxtFocusListener(compTab1);
        txt.setLayoutData(new GridData(GridData.FILL_BOTH));
        txt.addFocusListener(txtFL);
        txt.setText(TxtFocusListener.introText); txt.setForeground(compTab1.getDisplay().getSystemColor(SWT.COLOR_GRAY));
        new Label(compTab1, SWT.NONE);
        //new Label(compTab1, SWT.NONE);
               
//#########################################################################################################################        
        
        //TAB2 CONTENT
//        //This is the checks check box tree 
        GridLayout groupLayoutChecks = new GridLayout();
        groupLayoutChecks.numColumns = 3;
        Group groupChecks = new Group(compTab2, SWT.NONE);       
        groupChecks.setLayout(groupLayoutChecks);
        groupChecks.setLayoutData(new GridData(GridData.FILL_BOTH));
        
        GridData checksGridData2 = new GridData(GridData.BEGINNING, GridData.FILL_VERTICAL);
        checksGridData2.widthHint = 400;
        QueryDatabase qrydb = new QueryDatabase();
        List<HashMap<Integer, String>> checkList = qrydb.getFullCheckList();
        //System.out.println(checkList);
        CheckListTree clt = CheckListTree.getInstance();
        clt.createCheckListTree(groupChecks, checksGridData2, checkList);
        //new Label(groupChecks, SWT.NONE);
        //new Label(compTab2, SWT.NONE);     
        
        //This creates a label on the right side of the 
        //window to provide information  about each check
        helpLabel = new Label(groupChecks, SWT.BORDER); 
        GridData checksGridData22 = new GridData(GridData.FILL_BOTH);
        checksGridData22.widthHint = 700;
        helpLabel.setSize(300,300);
        helpLabel.setLocation(0, 0);
        helpLabel.setLayoutData(checksGridData22);  
        
        
        Map<Integer, TreeItem> checkListMap = new HashMap<Integer, TreeItem>();
        Map<Integer, String> checkNameMap= new HashMap<Integer, String>();
        checkNameMap = CheckListTree.getInstance().getCheckedStandards(checkListMap, checkNameMap);
        //If there are no checks selected then disable the RunChecks button
        if (checkNameMap.get(checkListMap) == null){
            item23.setEnabled(false); 
        } else {
         // do not do anything
        } 
 
//#########################################################################################################################
        
        //TAB3 CONTENT
        GridLayout groupLayoutResults = new GridLayout();
        groupLayoutChecks.numColumns = 2;
        Group groupResults = new Group(compTab3, SWT.NONE);       
        groupResults.setLayout(groupLayoutResults);
        groupResults.setLayoutData(new GridData(GridData.FILL_BOTH));
        
        
        //This is the progress bar
        //GridLayout progressBarGridLayout = new GridLayout();
        //progressBarGridLayout.numColumns = 1;
        GridData progressBarGridData = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
        RunCheckProgressBar progressBar = new RunCheckProgressBar();
        progressBar.createProgressBar(groupResults, progressBarGridData);
        
        //This is the results table
        Table table = new Table(groupResults, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
        //GridData resultsGridData = new GridData(1, 100, false, false);
        //table.setLayoutData(resultsGridData);
        table.setHeaderVisible(true);
        table.getVerticalBar().setVisible(true);
        //String[] titles = { "Override", "Rerun", "Status", "Check", "Filename", "Existing Line Numbers", "New Line Numbers" };
        String[] titles = { "Status", "Check", "Filename", "Existing Line Numbers", "New Line Numbers" };
        
        for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
            TableColumn column = new TableColumn(table, SWT.NULL);
            column.setText(titles[loopIndex]);
            //column.setWidth(80);
        }
        
        runPerl.setTable(table, titles);
        runPerl.setShell(shell, display);
        toolBarListener.setTable(table,titles);
                 
         GridData tableGridData = new GridData(GridData.FILL_BOTH);
         //data3.verticalAlignment = SWT.TOP;
         //data3.horizontalAlignment = SWT.LEFT;
         //data3.horizontalSpan = 4;
         
         int frameX = shell.getSize().x;
         tableGridData.widthHint = frameX;
         table.setLayoutData(tableGridData);
         
         for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
             table.getColumn(loopIndex).pack();
        }
       table.setRedraw(true);
         //new Label(compTab3, SWT.NONE);
             
//###############################################################
     
        shell.addShellListener(new ShellListener() {

            public void shellIconified(ShellEvent e) {
            }
            public void shellDeiconified(ShellEvent e) {
            }
            public void shellDeactivated(ShellEvent e) {
            }
            public void shellClosed(ShellEvent e) {
                System.out.println("Client Area: " + shell.getClientArea());
            }
            public void shellActivated(ShellEvent e) {
                int frameX = shell.getSize().x - shell.getClientArea().width;
                int frameY = shell.getSize().y - shell.getClientArea().height;
                shell.setSize(1200 + frameX, 1000 + frameY);
            }
        });
             
        shell.pack();
        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }
    
    public static String getFileList(){      
        return txt.getText();
    }
    
    
    public static void populateResultsTable(List<CheckDetail> checkDetails, Shell shell, Table table, String[] titles, boolean newRun){
    
        //ParseResultsXML parseResultsXML = new ParseResultsXML();
        
        //List<CheckDetail> checkDetails = parseResultsXML.getResultsXMLData();
        //CheckDetail checkDetail = new CheckDetail();

        if (newRun){
            table.removeAll();
        }else{
            //do not clean table            
        }
        boolean evenRow = true;
        for(Iterator<CheckDetail> i = checkDetails.iterator();i.hasNext();) {
            CheckDetail checkDetail = i.next();
            TableItem item = new TableItem(table, SWT.NULL);
            item.setText(0, checkDetail.getStatus()); //Status
            item.setText(1, checkDetail.getName()); //Check
            item.setText(2, checkDetail.getFileName()); //Filename
            item.setText(3, checkDetail.getExistingLineNumbers()); //Existing Line Numbers
            item.setText(4, checkDetail.getNewLineNumbers()); //New Line Numbers
            
            //This is to make shadow for every other line
            if (evenRow)
                item.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
            evenRow = !evenRow;
            
            i.remove(); // clear
         }
         
         for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
              table.getColumn(loopIndex).pack();
         }
        table.setRedraw(true);
    }
} 

Open in new window


RUNPERL.JAVA
public class RunPerl {
    
    
    static List<CheckDetail> checkDetails = null;
    static List<CheckDetail> checkDetailsAll = new ArrayList<CheckDetail>();    
    static FileTree fileTree = new FileTree();
    
    private static Shell shell;
    private static Table table;
    private static String[] titles;
    private static Display display;
    //static Text txt;
    
    public static String[] getFileList(){
        String[] Filelist = null;
        
        return Filelist;
    }
    
//    public static void stopProcess(){    
//        mtcheck_process.destroy();
//    }

        public static List<CheckDetail> runMtcheck() throws IOException {
            Set<String> results = null;
            
           
            //get the list of files from the text field in TAB1 
            //fileTree.main(null);
            String content = Gui.getFileList();
            
            //seperate the text by new line characters
            //and assign them to an array
            String fileData[] = content.split("(" + System.getProperty("line.separator") + ")+");
            
            
            //get the list of checks from the checks list in TAB2
            Map<Integer, TreeItem> checkListMap = new HashMap<Integer, TreeItem>();
            Map<Integer, String> checkNameMap= new HashMap<Integer, String>();
            checkNameMap = CheckListTree.getInstance().getCheckedStandards(checkListMap, checkNameMap);
               
            String tempDir = null;
            StringBuilder checkList = new StringBuilder();
            Iterator<Map.Entry<Integer, String>> it_checkNameMap = checkNameMap.entrySet().iterator();
            // loop through the hashmap and create the checks list
            while (it_checkNameMap.hasNext()) {
                Map.Entry<Integer, String> pairs_checkNameMap = it_checkNameMap.next();
                checkList.append(" -guiCheck ").append(pairs_checkNameMap.getValue());
            }
            
            
             //loop through each line (request) in the text box
            
            String perlCmd;
            String mtcheckCmd;
            String setMtcheckPathCmd;
            String sandboxLocation = null;
            String batchFileCmd = null;
            //FutureTask<CheckRunner> task = new FutureTask(myRunner);
            //ExecutorService checkExecutor = Executors.newFixedThreadPool(5);
           ExecutorService checkExecutor = Executors.newSingleThreadExecutor();
            HashMap<String, Future> futures = new HashMap<String,Future>(fileData.length);
            //int j = 0;
            for (int j = 0; j < fileData.length; j++){

                    String fileInfoLine = fileData[j];
                    String OS = System.getProperty("os.name").toLowerCase();
                    //String lineBreak = System.getProperty("line.separator");
                    //fileInfoLine = fileInfoLine.replaceAll(lineBreak, " ");
                    fileInfoLine = fileInfoLine.replaceAll("\\r|\\n", "");
                    Pattern sandboxLocPattern = Pattern.compile("(?<=(-f|-d|-d -r|-c)).+?(?=(?:matlab))");
                    Matcher matchSandboxLoc = sandboxLocPattern.matcher(fileInfoLine);
                    if (matchSandboxLoc.find()){
                        sandboxLocation = matchSandboxLoc.group();
                        fileInfoLine = fileInfoLine.replace(sandboxLocation," ");
                        sandboxLocation = sandboxLocation.replaceAll("-f|-d|-d -r|-c", "");
                    } else{
                        
                    }
                    
                    if (OS.indexOf("win") >= 0){
                        tempDir = "C:/Temp/mtcheck";
                        batchFileCmd = "cmd.exe /C \\\\some\\path\\in\\here\\standards\\main\\bin\\mtcheckGui.bat" +" " + sandboxLocation + " " + fileInfoLine + " " + checkList ;
                    }
                    else{ 
                           // this else will be implemented for UNIX and MAC later
                    }
                    
                    perlCmd = batchFileCmd;
                    CheckRunner myRunner = new CheckRunner();
                    myRunner.setCommand(perlCmd);
                    futures.put(fileInfoLine, checkExecutor.submit(myRunner));       
             }
            
            
            boolean exitLoop = false;
            boolean newRun = true;
            
            //Disable the runCheck button in the 2nd tab 
            //to prevent the user from using it
            //while the other processes are running.
             Gui.item23.setEnabled(false);
             String fileName = null;
            while(true && exitLoop == false) {
                
            HashMap<String, Future> tempFutures = futures;   
            ArrayList<String> keyList = new ArrayList<String>();
            
            for (Entry<String, Future> entry  : tempFutures.entrySet()) {
                Future<List<CheckDetail>> f = entry.getValue();
                    try {
                        List<CheckDetail> checkDetails = f.get(1, TimeUnit.MILLISECONDS);
                        
                        if (checkDetails != null) {
                            keyList.add(entry.getKey());
                            checkDetailsAll.addAll(checkDetails); 
                            Gui.populateResultsTable(checkDetails,shell,table,titles, newRun);
                            newRun = false;
                        }
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (TimeoutException e) {
                       ;
                    }
                }    

            if (!futures.isEmpty()){             
                for (String key : keyList) {
                    futures.remove(key);
                }                        
            }
            
            if (futures.isEmpty())
               exitLoop = true;
            }

            checkExecutor.shutdown();
            Gui.item23.setEnabled(true);
                        
            return checkDetailsAll;
        }
        
        public void setTable(Table table, String[] titles) {
            RunPerl.table = table;
            RunPerl.titles = titles;
        }  
        
        
        public void setShell(Shell shell, Display display) {
            RunPerl.shell = shell; 
            RunPerl.display = display;
        }
        
        
        public static void saveResults(String file) throws ParserConfigurationException{
            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            //get current date time with Date()
            Date date = new Date();

            
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.newDocument();
         
            Element rootElement = doc.createElement("Results");
            doc.appendChild(rootElement);
            
            Element dateElement = doc.createElement("Date");
            rootElement.appendChild(dateElement);
            dateElement.setTextContent(dateFormat.format(date));
            
            for (CheckDetail checkDetail : checkDetailsAll) {
                Element detailElement = doc.createElement("Detail");
                rootElement.appendChild(detailElement);

                Element nameElement = doc.createElement("name");
                detailElement.appendChild(nameElement);
                nameElement.setTextContent(checkDetail.getFileName());

                Element checkElement = doc.createElement("check");
                detailElement.appendChild(checkElement);
                checkElement.setTextContent(checkDetail.getName());

                Element statusElement = doc.createElement("status");
                detailElement.appendChild(statusElement);
                statusElement.setTextContent(checkDetail.getStatus());

                Element existingLineNumbersElement= doc.createElement("existingLineNumbers");
                detailElement.appendChild(existingLineNumbersElement);
                existingLineNumbersElement.setTextContent(checkDetail.getExistingLineNumbers());

                Element newLineNumbersElement= doc.createElement("newLineNumbers");
                detailElement.appendChild(newLineNumbersElement);
                newLineNumbersElement.setTextContent(checkDetail.getNewLineNumbers());

            }


            Transformer transformer = null;
            try {
                transformer = TransformerFactory.newInstance().newTransformer();
            } catch (TransformerConfigurationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (TransformerFactoryConfigurationError e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    
   
            // This is to serialize to a File
            FileWriter fileWriter = null;
            try {
                fileWriter = new FileWriter(file);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                transformer.transform(new DOMSource(doc), new StreamResult(fileWriter));
            } catch (TransformerException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            try {
                fileWriter.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
}

Open in new window


CHECKRUNNER.JAVA
public class CheckRunner implements Callable<List<CheckDetail>> {
    protected String resultsXML;
    protected String execCmd;
    static List<CheckDetail> checkDetails = null;
    static List<CheckDetail> checkDetailsAll = new ArrayList<CheckDetail>();
    
   public void setCommand(String perlCmd)
   {
       execCmd = perlCmd;
   }
   
   public List<CheckDetail> call() {
      Process mtcheck_process = null;
     //get the environment variables
       Map<String, String> env = System.getenv();
       String [] environment = new String[env.size()];
       int i = 0;
       for (Map.Entry<String, String> entry : env.entrySet())
       {
           environment[i] = entry.getKey() + "=" + entry.getValue();
           i++;
       }
       
       Runtime mtcheck_runtime = Runtime.getRuntime();
       
       
       try {
           mtcheck_process = mtcheck_runtime.exec(execCmd, environment);
       } catch (Exception e) {
           System.out.println("error executing " + execCmd);
       }
       

       /* dump output stream */
       InputStream is = mtcheck_process.getInputStream();
       BufferedReader reader = new BufferedReader
           ( new InputStreamReader(is));
       String commandLineOutput;
         
       try {
        while ((commandLineOutput = reader.readLine()) != null) {
               
               Pattern p = Pattern.compile("\\d{8}_\\d{4}_\\d{2}_.*?_Mtcheck_CodingStandards_ALL_Files.xml");
               Matcher m = p.matcher(commandLineOutput);
               if (m.find()){
                   resultsXML = m.group();                       
               }
               System.out.println(commandLineOutput);
           }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
       System.out.flush(); 
       
       /* print final result of process */
       System.err.println("Exit status=" + mtcheck_process.exitValue());
       
       String tempDir = null;
       String OS = System.getProperty("os.name").toLowerCase();
       
       if (OS.indexOf("win") >= 0){
           tempDir = "C:/Temp/mtcheck";
       } else{
           tempDir = "/tmp/mtcheck";
       }
       
       //get the name of the  generated XML from the CLI 
       //and parse it to generate the results table
       String path2ResultsXML = tempDir + "/" + resultsXML;
       new ParseResultsXML().parse(path2ResultsXML);
       checkDetails = new ParseResultsXML().parse(path2ResultsXML);
       return checkDetails;
}

    public List<CheckDetail> getList()
{
    return checkDetailsAll;
}
}

Open in new window

0
 
TolgarAuthor Commented:
@mccarl: I will make the change you recommended for the listener. I am waiting for your comments for the other parts of the code that I just sent.

I really appreciate your help.

Thanks!
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
mccarlConnect With a Mentor IT Business Systems Analyst / Software DeveloperCommented:
Ok, so here is your Gui.java file with a couple of changes so the gui updates occur is the gui thread...
public class Gui {

    static Display display;

    static ToolItem item_selectFilesDirectories;
    static ToolItem item_selectChangelist;
    static ToolItem item_selectFileList;
    static ToolItem item_clearList;
    static ToolItem item_SaveFileList;
    static ToolItem item13;
    static ToolItem item23;
    static CTabFolder folder;
    static ToolItem item2;
    static ToolItem item22;
    static ToolItem item222;
    static ToolItem item3;
    static ToolItem item33;
    static ToolItem item333;
    static ToolItem item3333;
    static ToolItem item33333;
    static ToolItem item333333;
    static ToolItem item3333333;
    static ToolItem item33333333;
    static ToolItem item_selectAllChecks;
    static Text txt;
    static Label helpLabel;

    
    private static ToolBarListener toolBarListener = new ToolBarListener();
    private static RunPerl runPerl = new RunPerl();
    static RWFile rwFile = new RWFile();
    static FileTree fileTree = new FileTree();
    //static ChangeListDlg changeListDlg = new ChangeListDlg(null);
    static StringBuilder buffer; 
    //static CheckListTree checks = new CheckListTree();
    
    
    public static void swichTabChecks() {
        folder.setSelection(1);
    }
    public static void swichTabResults() {
        folder.setSelection(2);
    }
    public static void swichTabFiles() {
        folder.setSelection(0);
    } 
    public static void readTxt(String fileListFile, String fileListPath) {
        buffer = new StringBuilder();
        buffer.append(txt.getText() + rwFile.readFromFile(fileListFile, fileListPath));
        String fileList = buffer.toString();
        
        txt.setText(fileList);
    }    
    public static void writeTxt(String file) {
        String content = txt.getText();
        
        //content = content.replaceAll("Use the buttons above to select files/directories, changelists, or saved file. Or you can type a list of fully-qualified names", "");
        //content = content.replaceAll("\\*", "");
        
        //Remove all empty lines
        content = content.replaceAll("(?m)^[ \t]*\r?\n", "");
        rwFile.writeToFile(content, file);
    }    
    public static void clearTxt() {
        txt.setText("");
        //txt.setText("Use the buttons above \n********************************\r\n");
    } 
    public static void selectFilesFolders() {
        fileTree.main(null);
        buffer = new StringBuilder();
        buffer.append(txt.getText() + "\r" + fileTree.getFileFolders());
        //System.out.println("FILES:" + fileTree.getFileFolders());
        String fileList = buffer.toString();
        txt.setText(fileList);
    }  
    
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        display = new Display();
        final Shell shell = new Shell(display);
        shell.setLocation(300,100);
        
        toolBarListener.setShell(shell,display);                  
        shell.setText("Development Desktop Tool");
        shell.setLayout(new GridLayout());        
        
        folder = new CTabFolder(shell, SWT.TOP);
        folder.setLayoutData(new GridData(SWT.FILL, GridData.FILL, true, true, 3, 3));
        CTabItem cTabItem1 = new CTabItem(folder, SWT.NONE);
        cTabItem1.setText("Files");
        CTabItem cTabItem2 = new CTabItem(folder, SWT.NONE);
        cTabItem2.setText("Checks");
        CTabItem cTabItem3 = new CTabItem(folder, SWT.NONE);
        cTabItem3.setText("Results");
       
     // -----------here starts TAB 1 -------------------- 
        Image image_Folder = new Image(display, "folder.png");
        Image image_shape_triangle = new Image(display, "shape_triangle.png");
        Image image_document = new Image(display, "document.png");
        Image image_delete = new Image(display, "delete.png");
        Image image_floppy_disk = new Image(display, "floppy_disk.png");
        Image image_navigate_right = new Image(display, "navigate_right.png");
       
        Composite compTab1 = new Composite(folder, SWT.NULL);
        GridLayout gridLayout1 = new GridLayout(3, false);
        compTab1.setLayout(gridLayout1);
        //compTab1.setLayoutData(new GridData());
        
        Composite compTB1 = new Composite(compTab1, SWT.NULL);
        GridLayout gL1 = new GridLayout(6, false);
        gL1.marginLeft = 0; gL1.marginRight = 0; gL1.horizontalSpacing = 0;
        compTB1.setLayout(gL1);
        GridData sepGD1 = new GridData(GridData.FILL_HORIZONTAL); sepGD1.horizontalSpan = 3; 
        compTB1.setLayoutData(sepGD1);
        compTB1.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_GRAY));
        
                
        //1st group
        CustomToolbar custToolBar1 = new CustomToolbar(compTB1, SWT.FLAT, "Files");
        
        item_selectFilesDirectories = new ToolItem(custToolBar1.getToolBar(), SWT.NONE);
        item_selectFilesDirectories.setImage(image_Folder); item_selectFilesDirectories.setText("Select Files/Directories"); item_selectFilesDirectories.setToolTipText("Select the files or the directory you want to analyze");
        item_selectFilesDirectories.addListener(SWT.Selection, toolBarListener);
        
        item_selectChangelist = new ToolItem(custToolBar1.getToolBar(), SWT.PUSH);
        item_selectChangelist.setImage(image_shape_triangle); item_selectChangelist.setText("Select Changelist"); item_selectChangelist.setToolTipText("Select the files in the changelist");
        item_selectChangelist.addListener(SWT.Selection, toolBarListener);
                
        item_selectFileList = new ToolItem(custToolBar1.getToolBar(), SWT.PUSH);
        item_selectFileList.setImage(image_document); item_selectFileList.setText("Select File List"); item_selectFileList.setToolTipText("Select the file list");
        item_selectFileList.addListener(SWT.Selection, toolBarListener);
        
        item_clearList = new ToolItem(custToolBar1.getToolBar(), SWT.PUSH);
        item_clearList.setImage(image_delete); item_clearList.setText("Clear List"); item_clearList.setToolTipText("Delete the list of all files below");
        item_clearList.addListener(SWT.Selection, toolBarListener);
        
        //This is the separator
        Label verticalSepartor11 = new Label(compTB1, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor11.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor11.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
        
        //2nd group
        CustomToolbar custToolBar11 = new CustomToolbar(compTB1, SWT.FLAT, "Configuration");
        
        item_SaveFileList = new ToolItem(custToolBar11.getToolBar(), SWT.NONE);
        item_SaveFileList.setImage(image_floppy_disk); item_SaveFileList.setText("Save"); item_SaveFileList.setToolTipText("Save the list of files below to text file for future reference");
        item_SaveFileList.addListener(SWT.Selection, toolBarListener);    
        
        
        //This is the separator
        Label verticalSepartor12 = new Label(compTB1, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor12.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor12.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
       
        //3rd group
        CustomToolbar custToolBar111 = new CustomToolbar(compTB1, SWT.FLAT, "Next Actions");
        
        item13 = new ToolItem(custToolBar111.getToolBar(), SWT.NONE);
        item13.setImage(image_navigate_right); item13.setText("Specify Checks"); item13.setToolTipText("Move to the next tab to select the list of checks. This icon will be enabled once you have information in the below text box with no path issues.");
        item13.addListener(SWT.Selection, toolBarListener);
  
        //This is the separator
        Label verticalSepartor13 = new Label(compTB1, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor13.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor13.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
        
        //This is the separator between the toolbar and the text box.
        Label horSepartorTab1 = new Label(compTab1, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.HORIZONTAL);
        GridData sepGridDataTab1 = new GridData(GridData.FILL_HORIZONTAL); sepGridDataTab1.horizontalSpan = 3; 
        horSepartorTab1.setLayoutData(sepGridDataTab1);horSepartorTab1.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
               
        Composite compButtons1 = new Composite(compTab1, SWT.NULL);
        FillLayout fillLayout1 = new FillLayout();
        fillLayout1.type = SWT.HORIZONTAL;                  
        compButtons1.setLayout(fillLayout1);
       
        cTabItem1.setControl(compTab1);
        
// -----------here starts TAB 2 --------------------              
        Image image_folder_document = new Image(display, "folder_document.png");
        Image image_selection_delete_2 = new Image(display, "selection_delete_2.png");
        //Image image_selectAllChecks = new Image(display, "selectAllChecks.png");

        Composite compTab2 = new Composite(folder, SWT.NULL);
        GridLayout gridLayout2 = new GridLayout(2, false);
        compTab2.setLayout(gridLayout2);
        
        Composite compTB2 = new Composite(compTab2, SWT.NULL);
        GridLayout gL2 = new GridLayout(4, false);
        gL2.marginLeft = 0; gL2.marginRight = 0; gL2.horizontalSpacing = 0;
        compTB2.setLayout(gL2);
        GridData sepGD2 = new GridData(GridData.FILL_HORIZONTAL); sepGD2.horizontalSpan = 2; 
        compTB2.setLayoutData(sepGD2);
        compTB2.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_GRAY));
        
        
        //1st group
        CustomToolbar custToolBar2 = new CustomToolbar(compTB2, SWT.FLAT, "Configuration");  
     
        item2 = new ToolItem(custToolBar2.getToolBar(), SWT.PUSH);
        item2.setImage(image_folder_document); item2.setText("Load saved check list"); item2.setToolTipText("Load the saved list of checks if you saved from previous runs");      
        item2.addListener(SWT.Selection, toolBarListener);
        
        item22 = new ToolItem(custToolBar2.getToolBar(), SWT.PUSH);
        item22.setImage(image_selection_delete_2); item22.setText("Unselect all"); item22.setToolTipText("Unselec all checks below");
        item22.addListener(SWT.Selection, toolBarListener);
        
        item222 = new ToolItem(custToolBar2.getToolBar(), SWT.PUSH);
        item222.setImage(image_floppy_disk); item222.setText("Save selections"); item222.setToolTipText("Save the list of checks to a XML file for future reference");
        item222.addListener(SWT.Selection, toolBarListener);
        
        //This is the separator
        Label verticalSepartor21 = new Label(compTB2, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor21.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor21.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
        
            
        //2nd group
        CustomToolbar custToolBar22 = new CustomToolbar(compTB2, SWT.FLAT, "Next Actions");
                
        item23 = new ToolItem(custToolBar22.getToolBar(), SWT.PUSH);
        item23.setImage(image_navigate_right); item23.setText("Run checks"); item23.setToolTipText("Run the checks against the files you selected");
        item23.addListener(SWT.Selection, toolBarListener); 
                     
        //This is the separator
        Label verticalSepartor22 = new Label(compTB2, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor22.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor22.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
        
        //This is the separator between the toolbar and the checks tree.
        Label horSepartorTab2 = new Label(compTab2, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.HORIZONTAL);
        GridData sepGridDataTab2 = new GridData(GridData.FILL_HORIZONTAL); sepGridDataTab2.horizontalSpan = 3; 
        horSepartorTab2.setLayoutData(sepGridDataTab2);horSepartorTab2.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
               
        Composite compButtons2 = new Composite(compTab2, SWT.NULL);
        FillLayout fillLayout2 = new FillLayout();
        fillLayout2.type = SWT.HORIZONTAL;                  
        compButtons2.setLayout(fillLayout2);
       
        cTabItem2.setControl(compTab2);
     // -----------here starts TAB 3 --------------------      
        Image image_breakpoint = new Image(display, "breakpoint.png");
        Image image_redo = new Image(display, "redo.png");
        Image image_gecko = new Image(display, "gecko.png");
        Image image_navigate_left2 = new Image(display, "navigate_left2_orange.png");
        Image image_exit = new Image(display, "exit.png");
        
        Composite compTab3 = new Composite(folder, SWT.NULL);
        GridLayout gridLayout3 = new GridLayout(1, false);
        compTab3.setLayout(gridLayout3);
        
        Composite compTB3 = new Composite(compTab3, SWT.NULL);
        GridLayout gL3 = new GridLayout(10, false);
        gL3.marginLeft = 0; gL3.marginRight = 0; gL3.horizontalSpacing = 0;
        compTB3.setLayout(gL3);
        GridData sepGD3 = new GridData(GridData.FILL_HORIZONTAL); sepGD3.horizontalSpan = 5; 
        compTB3.setLayoutData(sepGD3);
        compTB3.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_GRAY));

       
        //1st group
        CustomToolbar custToolBar3 = new CustomToolbar(compTB3, SWT.FLAT, "Configuration");   
       
        item3 = new ToolItem(custToolBar3.getToolBar(), SWT.PUSH);
        item3.setImage(image_floppy_disk); item3.setText("Save"); item3.setToolTipText("Save the list of files and checks to a XML file for future reference");
        item3.addListener(SWT.Selection, toolBarListener);

        //This is the separator
        Label verticalSepartor31 = new Label(compTB3, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor31.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor31.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
        
        //2nd group
        CustomToolbar custToolBar33 = new CustomToolbar(compTB3, SWT.FLAT, "Processing");             
        
        item33 = new ToolItem(custToolBar33.getToolBar(), SWT.PUSH);
        item33.setImage(image_breakpoint); item33.setText("Stop checks"); item33.setToolTipText("Stop running the checks");
        item33.addListener(SWT.Selection, toolBarListener);
        
        item333 = new ToolItem(custToolBar33.getToolBar(), SWT.PUSH);
        item333.setImage(image_redo); item333.setText("Rerun failed"); item333.setToolTipText("Rerun failed checks");
        item333.addListener(SWT.Selection, toolBarListener);

        //This is the separator
        Label verticalSepartor32 = new Label(compTB3, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor32.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor32.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
       
        
        //3rd group       
        CSFilteringCheckBoxes checkBoxes = new CSFilteringCheckBoxes(compTB3, SWT.FLAT);
        
        //This is the separator
        Label verticalSepartor33 = new Label(compTB3, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor33.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor33.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
        
        
        //4th group
        CustomToolbar custToolBar3333 = new CustomToolbar(compTB3, SWT.FLAT, "Results");
        
        item33333 = new ToolItem(custToolBar3333.getToolBar(), SWT.PUSH);
        item33333.setImage(image_floppy_disk); item33333.setText("Save results"); item33333.setToolTipText("Save the results to HTML or XML file");
        item33333.addListener(SWT.Selection, toolBarListener);  
        
        item333333 = new ToolItem(custToolBar3333.getToolBar(), SWT.PUSH);
        item333333.setImage(image_gecko); item333333.setText("Save to geck"); item333333.setToolTipText("Save the results to a geck. Geck number will be asked when you click this button");
        item333333.addListener(SWT.Selection, toolBarListener);
      
        //This is the separator
        Label verticalSepartor34 = new Label(compTB3, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor34.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor34.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
        
               
        //5th group
        CustomToolbar custToolBar33333 = new CustomToolbar(compTB3, SWT.FLAT, "Next Actions");      
    
        item3333333 = new ToolItem(custToolBar33333.getToolBar(), SWT.PUSH);
        item3333333.setImage(image_navigate_left2); item3333333.setText("Start over"); item3333333.setToolTipText("Go back to the first tab to start over");
        item3333333.addListener(SWT.Selection, toolBarListener);
        item33333333 = new ToolItem(custToolBar33333.getToolBar(), SWT.PUSH);
        item33333333.setImage(image_exit); item33333333.setText("Quit"); item33333333.setToolTipText("Quit the tool");
        item33333333.addListener(SWT.Selection, toolBarListener);
        
        //This is the separator
        Label verticalSepartor35 = new Label(compTB3, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.VERTICAL);
        verticalSepartor35.setLayoutData(new GridData(GridData.FILL_VERTICAL)); verticalSepartor35.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
        //new Label(compTB3, SWT.NONE);
                              
        
        Composite compButtons3 = new Composite(compTab3, SWT.NULL);
        FillLayout fillLayout3 = new FillLayout();
        fillLayout3.type = SWT.HORIZONTAL;                  
        compButtons3.setLayout(fillLayout3);
       
        cTabItem3.setControl(compTab3);
        //new Label(compTab3, SWT.NONE);
        //new Label(compTab3, SWT.NONE);
       

        //This is the separator between the toolbar and the results table.
        Label horSepartorTab3 = new Label(compTab3, SWT.SEPARATOR | SWT.SHADOW_NONE | SWT.HORIZONTAL);
        GridData sepGridDataTab3 = new GridData(GridData.FILL_HORIZONTAL); sepGridDataTab3.horizontalSpan = 5; 
        horSepartorTab3.setLayoutData(sepGridDataTab3);horSepartorTab3.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_BLACK));
        
        // -----------here ends ALL TAB MENUS -------------------- 
        
        //TAB1 CONTENT
        //This is the text box   
        GridLayout groupLayout = new GridLayout();
        Group groupText = new Group(compTab1, SWT.NONE);
        groupText.setLayout(groupLayout);
        groupText.setLayoutData(new GridData(GridData.FILL_BOTH));
        groupText.setText("File List \r (Use the buttons above to select files/directories, changelists, or saved file. Or you can type a list of fully-qualified names)");
        txt = new Text(groupText, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
        TxtFocusListener txtFL = new TxtFocusListener(compTab1);
        txt.setLayoutData(new GridData(GridData.FILL_BOTH));
        txt.addFocusListener(txtFL);
        txt.setText(TxtFocusListener.introText); txt.setForeground(compTab1.getDisplay().getSystemColor(SWT.COLOR_GRAY));
        new Label(compTab1, SWT.NONE);
        //new Label(compTab1, SWT.NONE);
               
//#########################################################################################################################        
        
        //TAB2 CONTENT
//        //This is the checks check box tree 
        GridLayout groupLayoutChecks = new GridLayout();
        groupLayoutChecks.numColumns = 3;
        Group groupChecks = new Group(compTab2, SWT.NONE);       
        groupChecks.setLayout(groupLayoutChecks);
        groupChecks.setLayoutData(new GridData(GridData.FILL_BOTH));
        
        GridData checksGridData2 = new GridData(GridData.BEGINNING, GridData.FILL_VERTICAL);
        checksGridData2.widthHint = 400;
        QueryDatabase qrydb = new QueryDatabase();
        List<HashMap<Integer, String>> checkList = qrydb.getFullCheckList();
        //System.out.println(checkList);
        CheckListTree clt = CheckListTree.getInstance();
        clt.createCheckListTree(groupChecks, checksGridData2, checkList);
        //new Label(groupChecks, SWT.NONE);
        //new Label(compTab2, SWT.NONE);     
        
        //This creates a label on the right side of the 
        //window to provide information  about each check
        helpLabel = new Label(groupChecks, SWT.BORDER); 
        GridData checksGridData22 = new GridData(GridData.FILL_BOTH);
        checksGridData22.widthHint = 700;
        helpLabel.setSize(300,300);
        helpLabel.setLocation(0, 0);
        helpLabel.setLayoutData(checksGridData22);  
        
        
        Map<Integer, TreeItem> checkListMap = new HashMap<Integer, TreeItem>();
        Map<Integer, String> checkNameMap= new HashMap<Integer, String>();
        checkNameMap = CheckListTree.getInstance().getCheckedStandards(checkListMap, checkNameMap);
        //If there are no checks selected then disable the RunChecks button
        if (checkNameMap.get(checkListMap) == null){
            item23.setEnabled(false); 
        } else {
         // do not do anything
        } 
 
//#########################################################################################################################
        
        //TAB3 CONTENT
        GridLayout groupLayoutResults = new GridLayout();
        groupLayoutChecks.numColumns = 2;
        Group groupResults = new Group(compTab3, SWT.NONE);       
        groupResults.setLayout(groupLayoutResults);
        groupResults.setLayoutData(new GridData(GridData.FILL_BOTH));
        
        
        //This is the progress bar
        //GridLayout progressBarGridLayout = new GridLayout();
        //progressBarGridLayout.numColumns = 1;
        GridData progressBarGridData = new GridData(GridData.HORIZONTAL_ALIGN_CENTER);
        RunCheckProgressBar progressBar = new RunCheckProgressBar();
        progressBar.createProgressBar(groupResults, progressBarGridData);
        
        //This is the results table
        Table table = new Table(groupResults, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
        //GridData resultsGridData = new GridData(1, 100, false, false);
        //table.setLayoutData(resultsGridData);
        table.setHeaderVisible(true);
        table.getVerticalBar().setVisible(true);
        //String[] titles = { "Override", "Rerun", "Status", "Check", "Filename", "Existing Line Numbers", "New Line Numbers" };
        String[] titles = { "Status", "Check", "Filename", "Existing Line Numbers", "New Line Numbers" };
        
        for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
            TableColumn column = new TableColumn(table, SWT.NULL);
            column.setText(titles[loopIndex]);
            //column.setWidth(80);
        }
        
        runPerl.setTable(table, titles);
        runPerl.setShell(shell, display);
        toolBarListener.setTable(table,titles);
                 
         GridData tableGridData = new GridData(GridData.FILL_BOTH);
         //data3.verticalAlignment = SWT.TOP;
         //data3.horizontalAlignment = SWT.LEFT;
         //data3.horizontalSpan = 4;
         
         int frameX = shell.getSize().x;
         tableGridData.widthHint = frameX;
         table.setLayoutData(tableGridData);
         
         for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
             table.getColumn(loopIndex).pack();
        }
       table.setRedraw(true);
         //new Label(compTab3, SWT.NONE);
             
//###############################################################
     
        shell.addShellListener(new ShellListener() {

            public void shellIconified(ShellEvent e) {
            }
            public void shellDeiconified(ShellEvent e) {
            }
            public void shellDeactivated(ShellEvent e) {
            }
            public void shellClosed(ShellEvent e) {
                System.out.println("Client Area: " + shell.getClientArea());
            }
            public void shellActivated(ShellEvent e) {
                int frameX = shell.getSize().x - shell.getClientArea().width;
                int frameY = shell.getSize().y - shell.getClientArea().height;
                shell.setSize(1200 + frameX, 1000 + frameY);
            }
        });
             
        shell.pack();
        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }
    
    public static String getFileList(){      
        return txt.getText();
    }
    
    
    public static void populateResultsTable(final List<CheckDetail> checkDetails, final Shell shell, final Table table, final String[] titles, final boolean newRun){
        display.asyncExec(new Runnable() {
            public void run() {

        //ParseResultsXML parseResultsXML = new ParseResultsXML();
        
        //List<CheckDetail> checkDetails = parseResultsXML.getResultsXMLData();
        //CheckDetail checkDetail = new CheckDetail();

        if (newRun){
            table.removeAll();
        }else{
            //do not clean table            
        }
        boolean evenRow = true;
        for(Iterator<CheckDetail> i = checkDetails.iterator();i.hasNext();) {
            CheckDetail checkDetail = i.next();
            TableItem item = new TableItem(table, SWT.NULL);
            item.setText(0, checkDetail.getStatus()); //Status
            item.setText(1, checkDetail.getName()); //Check
            item.setText(2, checkDetail.getFileName()); //Filename
            item.setText(3, checkDetail.getExistingLineNumbers()); //Existing Line Numbers
            item.setText(4, checkDetail.getNewLineNumbers()); //New Line Numbers
            
            //This is to make shadow for every other line
            if (evenRow)
                item.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
            evenRow = !evenRow;
            
            i.remove(); // clear
         }
         
         for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
              table.getColumn(loopIndex).pack();
         }
        table.setRedraw(true);
      }
     });
    }
    
    
    public static void reenableItem23(){
        display.asyncExec(new Runnable() {
            public void run() {
                item23.setEnabled(true);
            }
        });
    }
}

Open in new window

Points to note about the above... On lines 3 & 78, I have moved you declaration of "Display display" so that display is now a class variable so that you it can be accessed from the next bit of code that I will talk about. On lines 480,481 & 515, 516, I have wrapped your code that does updates of the GUI elements in a call to display.asyncExec(). This is the 'magic' that takes that code and makes sure that it gets executed by the actual GUI thread rather than by this new thread that we create in my earlier post. And finally, lines 520-526 are the new method that is called just before the new thread finishes in the code in my earlier post that re-enabled the toolbar item. Again this is done inside a different thread to the GUI thread, but it is a GUI update so it needs to be wrapped in the display.asyncExec() call so that it does happen on the GUI thread.

This should be enough to get you going. We'll make sure that this works for you and then we can look at improving the efficiency, etc.
0
 
TolgarAuthor Commented:
Hi,
I am getting the following exception in line 475.

Exception in thread "Thread-0" org.eclipse.swt.SWTException: Invalid thread access

Open in new window


This is the code that causes the problem

    public static String getFileList(){      
        return txt.getText();    //-----> LINE 475
    }

Open in new window


How can I fix this problem?
0
 
TolgarAuthor Commented:
And this method is called by RunPerl.java class in the run runMtCheck method. (LINE 30 in here 2 previous post of mine):

            //get the list of files from the text field in TAB1 
            String content = Gui.getFileList();

Open in new window

0
 
TolgarAuthor Commented:
@mccarl -> FYI: I tried the following change but it didn't help:

    public static String getFileList(){    
        display.asyncExec(new Runnable() {
            public void run() {              
            }
        });  
        return txt.getText();
    }

Open in new window

0
 
TolgarAuthor Commented:
FYI: I found this article but I still couldn't make it work:

Maybe it can give you some idea:

http://coderzen.blogspot.com/2013/08/exception-in-thread-thread-0.html
0
 
TolgarAuthor Commented:
Any ideas?
0
 
TolgarAuthor Commented:
One more info:

When I debug the code, I get Text {*Wrong Thread*} error when I hover over txt in the following line which I posted earlier:

    public static String getFileList(){      
        return txt.getText();    // -----> THIS LINE
    }

Open in new window


So, the txt is not the new thread and the new thread cannot access the txt in the main thread.

How can I access a variable in another thread in Java?
0
 
TolgarAuthor Commented:
I found this article but I cannot figure out how I will implement it in my code:

http://90kts.com/2007/10/25/sharing-data-safely-between-java-threads/

ANY IDEAS?
0
 
mccarlConnect With a Mentor IT Business Systems Analyst / Software DeveloperCommented:
ANY IDEAS?
I do need time to sleep! ;)  Plus its the weekend here, so it's not as easy to get time to answer questions. You'll have to be patient with me...

As for you problem, you've got the general idea, ie. that you can't read the text from the GUI component when you aren't in the GUI thread, but unfortunately you can't use the display.asyncExec() trick because there is no way to return a value from it. That's because it doesn't actually run what is inside the asyncExec call straight away. It is just telling the GUI thread to "run this bit of code when you a chance".

So, what to do?? In this case, it is fairly easy.. you just need to "get" the value from the GUI component while you are still running in the GUI thread, before you start your new thread to do the work. In your ToolbarListener.java file add this line just before you create "new Thread(..."  (in between lines 11 & 12 of the code in my first post)   (and yes the "final" keyword at the start is necessary)
final String content = Gui.getFileList();

Open in new window

Now you can just pass that "content" as an argument to your runCheck() method (or runMtcheck() or whatever it's name is now) like...
List<CheckDetail> checkDetails = RunPerl.runCheck(content);

Open in new window

And finally, in RunPerl.java declare your runCheck method to take the String content as an argument and then you can remove the Gui.getFileList() call that's near the top of runCheck() method.

Hopefully, that will get you going.. It just depends if there are any other gui component accesses in there that I haven't spotted!
0
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.

All Courses

From novice to tech pro — start learning today.