Solved

How to create "Processing" message while process in going on in JAVA SWT GUI?

Posted on 2013-11-18
8
531 Views
Last Modified: 2013-11-20
Hi,
I am working on a GUI and in this GUI I populate some data that I read from a server in a table. Since the data can sometimes be big, the process takes long and and the window (shell) that has the table in it can become unresponsive. On the other hand, the data does not show up in the table until the whole process of reading data from the serer finishes.

This causes problem so that I would like to solve it with the following approach:

- While the process of reading data from the server is going on, there will be a transparent pop up dialog box that will say "Processing..." in the middle of the window.

- The data will show up on the table as it processes. It will not wait for the whole process.

Please  see the whole code below:

The beginning is about connecting to Perforce server.

LINES 270 through 327 is to read the data and to arrange it to be populated on the table

LINES 331 through 357 is to populate data on the table.

The end is about creating ok and cancel buttons.

The part that takes long time is 270 to 327.


 
import java.net.URISyntaxException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

import com.perforce.p4java.client.IClientSummary;
import com.perforce.p4java.core.IChangelist;
import com.perforce.p4java.core.IChangelistSummary;
import com.perforce.p4java.core.file.IFileSpec;
import com.perforce.p4java.exception.AccessException;
import com.perforce.p4java.exception.ConfigException;
import com.perforce.p4java.exception.ConnectionException;
import com.perforce.p4java.exception.NoSuchObjectException;
import com.perforce.p4java.exception.P4JavaException;
import com.perforce.p4java.exception.RequestException;
import com.perforce.p4java.exception.ResourceException;
import com.perforce.p4java.option.server.GetChangelistsOptions;
import com.perforce.p4java.option.server.GetClientsOptions;
import com.perforce.p4java.server.IOptionsServer;
import com.perforce.p4java.server.ServerFactory;

import org.eclipse.jface.viewers.TextCellEditor;


public class ChangeListDlg extends Dialog {
    
    public static SelectedFileFoldersModel model = new SelectedFileFoldersModel();
    
    public static String changelistNum = "";
    
    public String getFileFolders()
    {
        return model.getFileOrFolderData();
    }

    public ChangeListDlg(Shell parent) {
        super(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.APPLICATION_MODAL);
    }
    
    public void open() {
        Shell shell = new Shell(getParent(), getStyle());
        shell.setText("Select changelist");
        try {
			createContents(shell);
		} catch (ConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RequestException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ConfigException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchObjectException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ResourceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}               
        
        shell.pack();
        shell.open();
        
     // Move the dialog to the center of the top level shell.
        Rectangle shellBounds = getParent().getBounds();
        Rectangle dialogSize = shell.getBounds();

        shell.setLocation(
          shellBounds.x + (shellBounds.width - dialogSize.width) / 2,
          shellBounds.y + (shellBounds.height - dialogSize.height) / 2 );
        
        
        int frameX = shell.getSize().x - shell.getClientArea().width;
        int frameY = shell.getSize().y - shell.getClientArea().height;
        shell.setSize(500 + frameX, 300 + frameY);
        
        
        Display display = getParent().getDisplay();
        while (!shell.isDisposed()) {
          if (!display.readAndDispatch()) {
            display.sleep();
          }
        }
    }

    public List<IClientSummary> getAllPerforceWorkspaces(IOptionsServer p4d, String userName){
                        
            //for getting all the workspaces
            GetClientsOptions clientOptions = new GetClientsOptions(0, userName, null);
            List<IClientSummary> clientSummaryList = null;
			try {
				clientSummaryList = p4d.getClients(clientOptions);
			} catch (P4JavaException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            //System.out.println(clientSummaryList.size());           

        return clientSummaryList;
    }

    
    private void createContents(final Shell shell) throws ConnectionException, AccessException, RequestException, ConfigException, NoSuchObjectException, ResourceException, URISyntaxException {
    	
    	//Connect to Perforce Server
    	final IOptionsServer p4d = ServerFactory.getOptionsServer(
			        ServerFactory.DEFAULT_PROTOCOL_NAME 
			        + "://" + "someServer", null);
			
			p4d.setUserName("tolgar");			

			p4d.connect();
        

        String userName = System.getProperty("user.name");
        //Get the workspace and changelist information from Perforce
        List<IClientSummary> clientSummaryList = getAllPerforceWorkspaces(p4d, userName);
                
        shell.setLayout(new GridLayout(2, false));
        
       
//        Label label_submitted = new Label(shell, SWT.NONE);
//        label_submitted.setText("Type changelists");
//          GridData data_submitted = new GridData();
//          data_submitted.horizontalAlignment = SWT.FILL;
//          data_submitted.grabExcessHorizontalSpace = true;
//        label_submitted.setLayoutData(data_submitted);
             
        Label label_workspace = new Label(shell, SWT.NONE);
        label_workspace.setText("Workspace:");
        GridData data_workspace = new GridData();
        data_workspace.horizontalAlignment = SWT.LEFT;
        data_workspace.verticalAlignment = SWT.TOP;
        data_workspace.grabExcessHorizontalSpace = true;
        label_workspace.setLayoutData(data_workspace);
        
//        final Text text_submittedChangelist = new Text(shell, SWT.BORDER | SWT.NONE);
//        GridData data_textSubmittedChangelist = new GridData();
//        data_textSubmittedChangelist.horizontalAlignment = SWT.FILL;
//        data_textSubmittedChangelist.grabExcessHorizontalSpace = true;
//        text_submittedChangelist.setLayoutData(data_textSubmittedChangelist);
        
        final Combo combo_workspaces = new Combo(shell, SWT.READ_ONLY);
        GridData data_comboWorkspaces = new GridData();
        data_comboWorkspaces.horizontalAlignment = SWT.LEFT;
        //data_textSubmittedChangelist.grabExcessHorizontalSpace = true;
        combo_workspaces.setLayoutData(data_comboWorkspaces);
        combo_workspaces.setEnabled(true);
        //GridData data_comboWorkspaces = new GridData(GridData.FILL_HORIZONTAL);
        //combo_workspaces.setLayoutData(data_comboWorkspaces);
        
        
        //public static Table table;
    	final List<Integer> changeListsArray = new ArrayList<Integer>();
    	final List<StringBuilder> fileListArray = new ArrayList<StringBuilder>();
    	final List<String> stateArray = new ArrayList<String>();
    	final List<String> changeListDescriptionsArray = new ArrayList<String>();

        List<String> workspacesArray = new ArrayList<String>();
        final String[] changelistStateArray = {"Pending", "Shelved", "Submitted"};     
        
        //This is to create the data(changelist number, file name, description) in each column using P4JAVA
        final GetChangelistsOptions getoptions = new GetChangelistsOptions();
        //getoptions.setType(IChangelist.Type.SUBMITTED);
        for(IClientSummary eachChangeSummary : clientSummaryList){
            String eachClientName = eachChangeSummary.getName();
            workspacesArray.add(eachChangeSummary.getName());
        }
        
        //The following line will be deleted once p4java is used to get the workspaces
        //String items[] = { "Workspace # One", "Workspace # Two", "Workspace # Three" };
        
        //combo_workspaces.setItems(items); combo_workspaces.select(2);
        combo_workspaces.setItems(workspacesArray.toArray(new String[workspacesArray.size()]));


        // ----------- the table -----------------
        GridLayout groupLayoutTable = new GridLayout();
        Group groupTable = new Group(shell, SWT.NONE);       
        groupTable.setLayout(groupLayoutTable);        
        
        final Table table = new Table(groupTable, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.WRAP | SWT.MULTI | SWT.CENTER | SWT.CHECK );
        TextCellEditor edit =new TextCellEditor(table,SWT.V_SCROLL);
        GridData tableGridData = new GridData(GridData.FILL_BOTH);
        tableGridData.horizontalSpan = 2;
        tableGridData.horizontalAlignment = SWT.FILL;
        tableGridData.grabExcessHorizontalSpace = true;
        tableGridData.verticalAlignment = SWT.FILL;
        tableGridData.grabExcessVerticalSpace = true;
        groupTable.setLayoutData(tableGridData);
        
        table.setLinesVisible(true);
        table.setHeaderVisible(true);
        table.getVerticalBar().setVisible(true);
        final String[] titles = { " ", "  Status  ", "Changelist", "Files", "Description" };
        
        //This is to create the column titles
        for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
            TableColumn column = new TableColumn(table, SWT.NULL);
            column.setText(titles[loopIndex]);
        }
        
        int frameShellWidth = shell.getSize().x;
        tableGridData.widthHint = frameShellWidth;
        table.setLayoutData(tableGridData);
        
        for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
            table.getColumn(loopIndex).pack();
       }
      table.setRedraw(true);
        
        //String selectedWorkspace = combo_workspaces.getText();
        //if(eachClientName.contains(selectedWorkspace)){
        
        combo_workspaces.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) { 
            	
            	
            	//clear the table
            	table.removeAll();
            	table.setRedraw(true);
            	 
	        	for (String changelistState : changelistStateArray){
	                getoptions.setClientName(combo_workspaces.getText());
	                
	                if (changelistState.equalsIgnoreCase("Pending")){
	                	getoptions.setType(IChangelist.Type.PENDING);
	                } else if (changelistState.equalsIgnoreCase("Shelved")){
	                	getoptions.setType(IChangelist.Type.SHELVED);
	                } else if(changelistState.equalsIgnoreCase("Submitted")){
	                	getoptions.setType(IChangelist.Type.SUBMITTED);
	                }
	                	                
	                List<IChangelistSummary> changeLists = null;
					try {					
						changeLists = p4d.getChangelists(null, getoptions);
					} catch (P4JavaException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
	                //System.out.println(eachChangeSummary.getName() +" : "+eachChangeSummary.getDescription() );
	                    for(IChangelistSummary eachChangeList : changeLists){
	                    	
	                    	StringBuilder depotfiles = new StringBuilder();
	                    	changeListsArray.add(eachChangeList.getId());
	                    	changeListDescriptionsArray.add(eachChangeList.getDescription());
	                    	stateArray.add(changelistState);
	                    	System.out.println(eachChangeList.getId()+" - " + eachChangeList.getDescription());
	                    		
	                        IChangelist cinfo = null;
							try {
								cinfo = p4d.getChangelist(eachChangeList.getId());
							} catch (ConnectionException e3) {
								// TODO Auto-generated catch block
								e3.printStackTrace();
							} catch (RequestException e3) {
								// TODO Auto-generated catch block
								e3.printStackTrace();
							} catch (AccessException e3) {
								// TODO Auto-generated catch block
								e3.printStackTrace();
							}
	                        List<IFileSpec> filesList = null;
							try {
								filesList = cinfo.getFiles(true);
							} catch (ConnectionException e2) {
								// TODO Auto-generated catch block
								e2.printStackTrace();
							} catch (RequestException e2) {
								// TODO Auto-generated catch block
								e2.printStackTrace();
							} catch (AccessException e2) {
								// TODO Auto-generated catch block
								e2.printStackTrace();
							}
	                        try {
								filesList = p4d.getChangelistFiles(eachChangeList.getId());
							} catch (ConnectionException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							} catch (RequestException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							} catch (AccessException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
	                        for(IFileSpec eachFileSpec : filesList){
	                            System.out.println(eachFileSpec.getDepotPathString());
	                            String lineFeed = System.getProperty("line.separator");
	                            if (eachFileSpec.getDepotPathString() != null){
	                            	depotfiles = depotfiles.append(eachFileSpec.getDepotPathString() + lineFeed);
	                            } else{
	                            	depotfiles = depotfiles.append(eachFileSpec.getLocalPathString() + lineFeed);
	                            }
	                        }    
	                        fileListArray.add(depotfiles);
	                    }
	        	}
	        	
	        	
	        	
	            //This is to populate data in the table
	            for (int loopIndex = 0; loopIndex < changeListsArray.size(); loopIndex++) {
	              TableItem item = new TableItem(table, SWT.NULL);
	                           
//	        	  TableEditor editor = new TableEditor (table);
//	        	  Button checkButton = new Button(table, SWT.CHECK);
//	        	  checkButton.pack();
//	        	  editor.minimumWidth = checkButton.getSize ().x;
//	        	  editor.horizontalAlignment = SWT.CENTER;
//	        	  editor.setEditor(checkButton, item, 0);
	              
	              
	              item.setText(1, stateArray.get(loopIndex));
	              item.setText(2, changeListsArray.get(loopIndex).toString());
	              item.setText(3, fileListArray.get(loopIndex).toString());
	              item.setText(4, changeListDescriptionsArray.get(loopIndex));
	              //if (loopIndex % 2 == 0) item.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
	            }
	            
	            
	            
	            
	            for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
	                table.getColumn(loopIndex).pack();
	            }
	            
	            table.setRedraw(true);
	            
	            //clears the table
	            cleanList(changeListsArray, fileListArray, stateArray, changeListDescriptionsArray, table);
	            
	          //This is to sort the columns in the table
	            Listener sortListener = new Listener() {
	                int prevSortIndex = -1;
	                int prevSortDirection = 1;
                    int prevSortDir;
                    
	                public void handleEvent(Event e) {
	                    TableItem[] items = table.getItems();
	                    Collator collator = Collator.getInstance(Locale.getDefault());
	                    TableColumn column = (TableColumn) e.widget;
	                    int index = column == table.getColumn(0) ? 0 : 1;
	                    if (prevSortIndex == index) {
	                        prevSortDir *= -1;
	                    } else {
	                        prevSortDir = 1;
	                        prevSortIndex = index;
	                    }
	                    for (int i = 1; i < items.length; i++) {
	                        String value1 = items[i].getText(index);
	                        for (int j = 0; j < i; j++) {
	                            String value2 = items[j].getText(index);
	                            if ((collator.compare(value1, value2) * prevSortDir) < 0) {
	                                String[] values = { items[i].getText(0),
	                                        items[i].getText(1), items[i].getText(2),
	                                        items[i].getText(3) };
	                                items[i].dispose();
	                                TableItem item = new TableItem(table, SWT.NONE, j);
	                                item.setText(values);
	                                items = table.getItems();
	                                break;
	                            }
	                        }
	                    }
	                    table.setSortColumn(column);
	                }
	            };
	            
	            
	            table.getColumn(1).addListener(SWT.Selection, sortListener);
	            table.getColumn(2).addListener(SWT.Selection, sortListener);
	            table.setSortColumn(table.getColumn(1));
	            table.setSortDirection(SWT.TOP);
	            
	            table.setRedraw(true);
            }
          });
        
          //This is for multi-line cell
//        Listener paintListener = new Listener() {
//            public void handleEvent(Event event) {
//              switch (event.type) {
//              case SWT.MeasureItem: {
//                TableItem item = (TableItem) event.item;
//                String text = getText(item, event.index);
//                Point size = event.gc.textExtent(text);
//                event.width = size.x;
//                event.height = Math.max(event.height, size.y);
//                table.setRedraw(true);
//                break;
//              }
//              case SWT.PaintItem: {
//                TableItem item = (TableItem) event.item;
//                String text = getText(item, event.index);
//                Point size = event.gc.textExtent(text);
//                int offset2 = event.index == 0 ? Math.max(0, (event.height - size.y) / 2) : 0;
//                event.gc.drawText(text, event.x, event.y + offset2, true);
//                table.setRedraw(true);
//                break;
//              }
//              case SWT.EraseItem: {
//                event.detail &= ~SWT.FOREGROUND;
//                table.setRedraw(true);
//                break;
//              }
//              }
//            }
//
//            String getText(TableItem item, int column) {
//              String text = item.getText(column);
//              if (column != 0) {
//                int index = table.indexOf(item);
//                if ((index + column) % 3 == 1) {
//                  //text += "\nnew line";
//                }
//                if ((index + column) % 3 == 2) {
//                  //text += "\nnew line\nnew line";
//                }
//              }
//              table.setRedraw(true);
//              return text;
//            }
//          };
//        
//        
//        table.addListener(SWT.MeasureItem, paintListener);
//        table.addListener(SWT.PaintItem, paintListener);
//        table.addListener(SWT.EraseItem, paintListener);
        
        
        //Get the checked changelists from the table
        table.addListener(SWT.Selection, new Listener()
        {
            @Override
            public void handleEvent(Event event)
            {
                if(event.detail == SWT.CHECK)
                {
                    TableItem current = (TableItem)event.item;
                    String lineFeed = System.getProperty("line.separator");
                    if(current.getChecked())
                    {                    	
                    	//changelistNum = changelistNum + ","+ current.getText(2) + " -" + current.getText(1).toLowerCase() + " -> " + current.getText(3).replace(lineFeed, "");
                    	changelistNum = changelistNum + "-c " + current.getText(2) + " -" + current.getText(1).toLowerCase() + " ### " + current.getText(3);
                        System.out.println(current.getText(2));
                    } else{
                    	String removeIt = "-c " + current.getText(2) + " -" + current.getText(1).toLowerCase() + " ### " + current.getText(3);
                    	changelistNum = changelistNum.replace(removeIt, "");
                    }
                }
            }
        });
        
        GridData okButton = new GridData();
        okButton.horizontalAlignment = SWT.FILL;
        okButton.grabExcessHorizontalSpace = true;
        Button ok = new Button(shell, SWT.PUSH);
        ok.setText("Add files from this change list");
        ok.setLayoutData(okButton);
        ok.addSelectionListener(new SelectionAdapter() {
          public void widgetSelected(SelectionEvent event) {
            //String changeList = text_submittedChangelist.toString();
            //model.storeFileOrFolder(changeList);
            //populate changelist in the text box
            
            //if (!text_submittedChangelist.getText().isEmpty()){
            if (!changelistNum.isEmpty()){
	            //setChangelist(text_submittedChangelist.getText());
            	//changelistNum = changelistNum + "," + text_submittedChangelist.getText();
            	//This is a temporary solution to remove the null in the beginning of the changelist
            	//changelistNum.replaceAll("null", "");
            	//String changeListNumbers = changelistNum.replaceAll(",", "\r\n-c ");

	            //Replace multiple spaces with once space 
	            //changeListNumbers = changeListNumbers.replaceAll(" +", " ");
	            
	            
	            //Get the checked changelists from the table

	            
            
	            //populatechangelist("-c " + changelistNum + "\r\n");
            	populatechangelist(changelistNum);
	            shell.close();	
	            //disconnect from the Perforce server
	            disconnectFromServer(p4d);
	            changelistNum = "";
            }else{
            	shell.close();
                //disconnect from the Perforce server
            	disconnectFromServer(p4d);
            }
          }
        });

        Button cancel = new Button(shell, SWT.PUSH);
        cancel.setText("Cancel");
        GridData cancelButton = new GridData();
        cancelButton.horizontalAlignment = SWT.FILL;
        cancelButton.grabExcessHorizontalSpace = true;
        cancel.setLayoutData(cancelButton);
        cancel.addSelectionListener(new SelectionAdapter() {
          public void widgetSelected(SelectionEvent event) {
            shell.close();
          }
        });
        shell.setDefaultButton(ok);
        
    }
    
    public void disconnectFromServer(IOptionsServer p4d){
        //disconnect from the Perforce server
        try {
			p4d.disconnect();
		} catch (ConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
//    public void setChangelist(String changelistNumber){        
//        changelistNum = changelistNumber;
//    }
    
    
    public void populatechangelist(String changeLists){
        if (Gui.txt.getText().isEmpty()){
            Gui.txt.setText(Gui.txt.getText() + changeLists);
        } else{
            Gui.txt.setText(Gui.txt.getText() + "\r\n" +  changeLists);
        }
    }
    

    public static void cleanList(List<Integer> changeListsArray, List<StringBuilder> fileListArray, List<String> stateArray, List<String> changeListDescriptionsArray, Table table){
    	changeListsArray.removeAll(changeListsArray);
    	fileListArray.removeAll(fileListArray);
    	stateArray.removeAll(stateArray);
    	changeListDescriptionsArray.removeAll(changeListDescriptionsArray);
    	table.setRedraw(true);
    }
    
}

Open in new window

0
Comment
Question by:Tolgar
  • 5
  • 3
8 Comments
 
LVL 35

Expert Comment

by:mccarl
Comment Utility
You already have an example of using SwingWorker in your code. You will need to do pretty much the same thing here. To recap, SwingWorker helps you execute code in another thread which is what you need to do here so that the GUI stays responsive. It also handles updating the GUI from the correct thread with progress information, so you can use this to update your table with results as they are received.
0
 

Author Comment

by:Tolgar
Comment Utility
@mccarl: I think more clarification on this one because I am not very clear how the other one works. I made so many changes on it at the time I implemented it.
0
 

Author Comment

by:Tolgar
Comment Utility
Any ideas?
0
 
LVL 35

Accepted Solution

by:
mccarl earned 500 total points
Comment Utility
Ok, sorry I was not thinking straight when I posted that. SwingWorker is for Swing apps not SWT apps.

You need to use a separate thread to do the server querying and then do the GUI updates inside a Display.asyncExec() call (so that they get executed on the main UI thread). This example should give you an idea...

http://git.eclipse.org/c/platform/eclipse.platform.swt.git/tree/examples/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet130.java

Note that the "separate thread" part of that example, is mostly hidden inside that BusyIndicator.showWhile() method call, however this functionality is probably what you want, so you can just copy that.

Since this is possibly quite a complex change and it is impossible to run your code without the rest of your environment (perforce server and such), it will be hard for me to write the code for you (plus I don't get paid to do that ;)   Take the example, and make sure you know what is going on with that simple code and then try to apply that to your code.

Note: you might find the biggest challenge is to get the update to happen as the data comes in from the server. The problem is that you current code is structured quite differently, ie. it gathers all the data into List objects and only then does it start constructing the table. You will have to change that all around to be able to get the GUI to update "as you go".
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

Author Comment

by:Tolgar
Comment Utility
Hmmm. This seems like a pretty complex task for such a small gain. And I know I proposed this type of solution in my question.

Do you think there can be different solution to solve this problem?

The two hard requirements that I have are:

- user should be able to close the dialog box (shell) at any point he wants
- the "not responding" message should not show up on the top part of the dialog box ( shell)
0
 

Author Comment

by:Tolgar
Comment Utility
@mccarl: I used the same logic in the site that you sent me and I am ok to put the data all at once to the table and I managed to do it.

However, even though the data generation is completed, the busy indicator keeps spinning. I can still use the controls on the shell but it is misleading for the user as if the process is still going on.  

Can you please help me to figure out how to make the busy indicator disappear after the process is completed?

This my code after the changes:


public class ChangeListDlg extends Dialog {
    
    public static SelectedFileFoldersModel model = new SelectedFileFoldersModel();
    public static Display display;
    public static String changelistNum = "";
    
    public String getFileFolders()
    {
        return model.getFileOrFolderData();
    }

    public ChangeListDlg(Shell parent) {
        super(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.APPLICATION_MODAL);
    }
    
    public void open() {
        Shell shell = new Shell(getParent(), getStyle());
        shell.setText("Select changelist");
        try {
			createContents(shell);
		} catch (ConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RequestException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ConfigException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchObjectException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ResourceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}               
        
        shell.pack();
        shell.open();
        
        
        int frameX = shell.getSize().x - shell.getClientArea().width;
        int frameY = shell.getSize().y - shell.getClientArea().height;
        shell.setSize(500 + frameX, 300 + frameY); 
        
        
     // Move the dialog to the center of the top level shell.
        Rectangle shellBounds = getParent().getBounds();
        Rectangle dialogSize = shell.getBounds();

        shell.setLocation(
          shellBounds.x + (shellBounds.width - dialogSize.width) / 2,
          shellBounds.y + (shellBounds.height - dialogSize.height) / 2 );
             
        
        display = getParent().getDisplay();
        while (!shell.isDisposed()) {
          if (!display.readAndDispatch()) {
            display.sleep();
          }
        }
    }

    public List<IClientSummary> getAllPerforceWorkspaces(IOptionsServer p4d, String userName){
                        
            //for getting all the workspaces
            GetClientsOptions clientOptions = new GetClientsOptions(0, userName, null);
            List<IClientSummary> clientSummaryList = null;
			try {
				clientSummaryList = p4d.getClients(clientOptions);
			} catch (P4JavaException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            //System.out.println(clientSummaryList.size());           

        return clientSummaryList;
    }

    
    private void createContents(final Shell shell) throws ConnectionException, AccessException, RequestException, ConfigException, NoSuchObjectException, ResourceException, URISyntaxException {
    	
    	//Connect to Perforce Server
    	final IOptionsServer p4d = ServerFactory.getOptionsServer(
			        ServerFactory.DEFAULT_PROTOCOL_NAME 
			        + "://" + "someserver", null);
			
			p4d.setUserName("tolgar");			

			p4d.connect();
        

        String userName = System.getProperty("user.name");
        //Get the workspace and changelist information from Perforce
        List<IClientSummary> clientSummaryList = getAllPerforceWorkspaces(p4d, userName);
                
        shell.setLayout(new GridLayout(1, false));

        Composite workspaceComp = new Composite(shell, SWT.NONE);
        workspaceComp.setLayout(new RowLayout());
        
        Label label_workspace = new Label(workspaceComp, SWT.NONE);
        label_workspace.setText("Workspace:");
            
        final Combo combo_workspaces = new Combo(workspaceComp, SWT.READ_ONLY);
        combo_workspaces.setEnabled(true);
        
        
        //public static Table table;
    	final List<Integer> changeListsArray = new ArrayList<Integer>();
    	final List<StringBuilder> fileListArray = new ArrayList<StringBuilder>();
    	final List<String> stateArray = new ArrayList<String>();
    	final List<String> changeListDescriptionsArray = new ArrayList<String>();

        List<String> workspacesArray = new ArrayList<String>();
        final String[] changelistStateArray = {"Pending", "Shelved", "Submitted"};     
        
        //This is to create the data(changelist number, file name, description) in each column using P4JAVA
        final GetChangelistsOptions getoptions = new GetChangelistsOptions();
        for(IClientSummary eachChangeSummary : clientSummaryList){
            String eachClientName = eachChangeSummary.getName();
            workspacesArray.add(eachChangeSummary.getName());
        }
        
        combo_workspaces.setItems(workspacesArray.toArray(new String[workspacesArray.size()]));


        // ----------- the table -----------------
        GridLayout groupLayoutTable = new GridLayout();
        Group groupTable = new Group(shell, SWT.NONE);       
        groupTable.setLayout(groupLayoutTable);        
        
        final Table table = new Table(groupTable, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.WRAP | SWT.MULTI | SWT.CENTER | SWT.CHECK );
        TextCellEditor edit =new TextCellEditor(table,SWT.V_SCROLL);
        GridData tableGridData = new GridData(GridData.FILL_BOTH);
        //tableGridData.horizontalSpan = 2;
        tableGridData.horizontalAlignment = SWT.FILL;
        tableGridData.grabExcessHorizontalSpace = true;
        tableGridData.verticalAlignment = SWT.FILL;
        tableGridData.grabExcessVerticalSpace = true;
        groupTable.setLayoutData(tableGridData);
        
        table.setLinesVisible(true);
        table.setHeaderVisible(true);
        table.getVerticalBar().setVisible(true);
        final String[] titles = { " ", "  Status  ", "Changelist", "Files", "Description" };
        
        //This is to create the column titles
        for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
            TableColumn column = new TableColumn(table, SWT.NULL);
            column.setText(titles[loopIndex]);
        }
        
        int frameShellWidth = shell.getSize().x;
        tableGridData.widthHint = frameShellWidth;
        table.setLayoutData(tableGridData);
        
        for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
            table.getColumn(loopIndex).pack();
       }
      table.setRedraw(true);
        
        //String selectedWorkspace = combo_workspaces.getText();
        //if(eachClientName.contains(selectedWorkspace)){
        
        combo_workspaces.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {            	
            	Runnable longJob = new Runnable() {
            	boolean done = false;
				@Override
				public void run() {
					Thread thread = new Thread(new Runnable() {
						@Override
						public void run() {
            	
								display.syncExec(new Runnable() {
									public void run() {
						            	//clear the table
						            	table.removeAll();
						            	table.setRedraw(true);
						            	 
							        	for (String changelistState : changelistStateArray){
							        		
							                getoptions.setClientName(combo_workspaces.getText());
							                
							                if (changelistState.equalsIgnoreCase("Pending")){
							                	getoptions.setType(IChangelist.Type.PENDING);
							                } else if (changelistState.equalsIgnoreCase("Shelved")){
							                	getoptions.setType(IChangelist.Type.SHELVED);
							                } else if(changelistState.equalsIgnoreCase("Submitted")){
							                	getoptions.setType(IChangelist.Type.SUBMITTED);
							                }
							                	                
							                List<IChangelistSummary> changeLists = null;
											try {					
												changeLists = p4d.getChangelists(null, getoptions);
											} catch (P4JavaException e1) {
												// TODO Auto-generated catch block
												e1.printStackTrace();
											}
							                //System.out.println(eachChangeSummary.getName() +" : "+eachChangeSummary.getDescription() );
							                    for(IChangelistSummary eachChangeList : changeLists){
							                    	
							                    	StringBuilder depotfiles = new StringBuilder();
							                    	changeListsArray.add(eachChangeList.getId());
							                    	changeListDescriptionsArray.add(eachChangeList.getDescription());
							                    	stateArray.add(changelistState);
							                    	System.out.println(eachChangeList.getId()+" - " + eachChangeList.getDescription());
							                    		
							                        IChangelist cinfo = null;
													try {
														cinfo = p4d.getChangelist(eachChangeList.getId());
													} catch (ConnectionException e3) {
														// TODO Auto-generated catch block
														e3.printStackTrace();
													} catch (RequestException e3) {
														// TODO Auto-generated catch block
														e3.printStackTrace();
													} catch (AccessException e3) {
														// TODO Auto-generated catch block
														e3.printStackTrace();
													}
							                        List<IFileSpec> filesList = null;
													try {
														filesList = cinfo.getFiles(true);
													} catch (ConnectionException e2) {
														// TODO Auto-generated catch block
														e2.printStackTrace();
													} catch (RequestException e2) {
														// TODO Auto-generated catch block
														e2.printStackTrace();
													} catch (AccessException e2) {
														// TODO Auto-generated catch block
														e2.printStackTrace();
													}
							                        try {
														filesList = p4d.getChangelistFiles(eachChangeList.getId());
													} catch (ConnectionException e1) {
														// TODO Auto-generated catch block
														e1.printStackTrace();
													} catch (RequestException e1) {
														// TODO Auto-generated catch block
														e1.printStackTrace();
													} catch (AccessException e1) {
														// TODO Auto-generated catch block
														e1.printStackTrace();
													}
							                        for(IFileSpec eachFileSpec : filesList){
							                            System.out.println(eachFileSpec.getDepotPathString());
							                            String lineFeed = System.getProperty("line.separator");
							                            if (eachFileSpec.getDepotPathString() != null){
							                            	depotfiles = depotfiles.append(eachFileSpec.getDepotPathString() + lineFeed);
							                            } else{
							                            	depotfiles = depotfiles.append(eachFileSpec.getLocalPathString() + lineFeed);
							                            }
							                        }    
							                        fileListArray.add(depotfiles);
							                    }
							        		}
							        	
							        	
								            //This is to populate data in the table
								            for (int loopIndex = 0; loopIndex < changeListsArray.size(); loopIndex++) {
								              TableItem item = new TableItem(table, SWT.NULL);
								                           
							//	        	  TableEditor editor = new TableEditor (table);
							//	        	  Button checkButton = new Button(table, SWT.CHECK);
							//	        	  checkButton.pack();
							//	        	  editor.minimumWidth = checkButton.getSize ().x;
							//	        	  editor.horizontalAlignment = SWT.CENTER;
							//	        	  editor.setEditor(checkButton, item, 0);
								              
								              
								              item.setText(1, stateArray.get(loopIndex));
								              item.setText(2, changeListsArray.get(loopIndex).toString());
								              item.setText(3, fileListArray.get(loopIndex).toString());
								              item.setText(4, changeListDescriptionsArray.get(loopIndex));
								              //if (loopIndex % 2 == 0) item.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
								            }
								            
								            for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
								            	table.getColumn(loopIndex).pack();
								            }
							            
							            table.setRedraw(true);
								        
							            //clears the table
							            cleanList(changeListsArray, fileListArray, stateArray, changeListDescriptionsArray, table);
							            
								        //This is to sort the columns in the table
							            Listener sortListener = new Listener() {
							                int prevSortIndex = -1;
							                int prevSortDirection = 1;
						                    int prevSortDir;
						                    
							                public void handleEvent(Event e) {
							                    TableItem[] items = table.getItems();
							                    Collator collator = Collator.getInstance(Locale.getDefault());
							                    TableColumn column = (TableColumn) e.widget;
							                    int index = column == table.getColumn(0) ? 0 : 1;
							                    if (prevSortIndex == index) {
							                        prevSortDir *= -1;
							                    } else {
							                        prevSortDir = 1;
							                        prevSortIndex = index;
							                    }
							                    for (int i = 1; i < items.length; i++) {
							                        String value1 = items[i].getText(index);
							                        for (int j = 0; j < i; j++) {
							                            String value2 = items[j].getText(index);
							                            if ((collator.compare(value1, value2) * prevSortDir) < 0) {
							                                String[] values = { items[i].getText(0),
							                                        items[i].getText(1), items[i].getText(2),
							                                        items[i].getText(3) };
							                                items[i].dispose();
							                                TableItem item = new TableItem(table, SWT.NONE, j);
							                                item.setText(values);
							                                items = table.getItems();
							                                break;
							                            }
							                        }
							                    }
							                    table.setSortColumn(column);
							                }
							            };
							            
							            
							            table.getColumn(1).addListener(SWT.Selection, sortListener);
							            table.getColumn(2).addListener(SWT.Selection, sortListener);
							            table.setSortColumn(table.getColumn(1));
							            table.setSortDirection(SWT.TOP);
							            
							            table.setRedraw(true);
							        	
										}
									});					        					        					            
								} //second public void run									
							}); //new Thread
							thread.start();
							while (!done && !shell.isDisposed()) {
								if (!display.readAndDispatch())
									display.sleep();
							}
					}
            	}; //first public void run
					BusyIndicator.showWhile(display, longJob);
            } //widgetSelected            
          }); //SelectionAdapter
        
					
					
          //This is for multi-line cell
//        Listener paintListener = new Listener() {
//            public void handleEvent(Event event) {
//              switch (event.type) {
//              case SWT.MeasureItem: {
//                TableItem item = (TableItem) event.item;
//                String text = getText(item, event.index);
//                Point size = event.gc.textExtent(text);
//                event.width = size.x;
//                event.height = Math.max(event.height, size.y);
//                table.setRedraw(true);
//                break;
//              }
//              case SWT.PaintItem: {
//                TableItem item = (TableItem) event.item;
//                String text = getText(item, event.index);
//                Point size = event.gc.textExtent(text);
//                int offset2 = event.index == 0 ? Math.max(0, (event.height - size.y) / 2) : 0;
//                event.gc.drawText(text, event.x, event.y + offset2, true);
//                table.setRedraw(true);
//                break;
//              }
//              case SWT.EraseItem: {
//                event.detail &= ~SWT.FOREGROUND;
//                table.setRedraw(true);
//                break;
//              }
//              }
//            }
//
//            String getText(TableItem item, int column) {
//              String text = item.getText(column);
//              if (column != 0) {
//                int index = table.indexOf(item);
//                if ((index + column) % 3 == 1) {
//                  //text += "\nnew line";
//                }
//                if ((index + column) % 3 == 2) {
//                  //text += "\nnew line\nnew line";
//                }
//              }
//              table.setRedraw(true);
//              return text;
//            }
//          };
//        
//        
//        table.addListener(SWT.MeasureItem, paintListener);
//        table.addListener(SWT.PaintItem, paintListener);
//        table.addListener(SWT.EraseItem, paintListener);
        
        
        //Get the checked changelists from the table
        table.addListener(SWT.Selection, new Listener()
        {
            @Override
            public void handleEvent(Event event)
            {
                if(event.detail == SWT.CHECK)
                {
                    TableItem current = (TableItem)event.item;
                    String lineFeed = System.getProperty("line.separator");
                    String fileFromChangelist = current.getText(3).replace(lineFeed, "") + " #### " + "-c " + current.getText(2) + " -" + current.getText(1).toLowerCase();
                    if(current.getChecked())
                    {                    	
                    	changelistNum = changelistNum + fileFromChangelist;
                        System.out.println(current.getText(2));
                    } else{
                    	String removeIt = fileFromChangelist;
                    	changelistNum = changelistNum.replace(removeIt, "");
                    }
                }
            }
        });
        

        Composite buttonComp = new Composite(shell, SWT.NONE);
        buttonComp.setLayout(new RowLayout());
        
        Button ok = new Button(buttonComp, SWT.PUSH);
        ok.setText("Add files from the selected changelist(s)");
        ok.addSelectionListener(new SelectionAdapter() {
          public void widgetSelected(SelectionEvent event) {
            if (!changelistNum.isEmpty()){
                    
            	populatechangelist(changelistNum);
	            shell.close();	
	            //disconnect from the Perforce server
	            disconnectFromServer(p4d);
	            changelistNum = "";
            }else{
            	shell.close();
                //disconnect from the Perforce server
            	disconnectFromServer(p4d);
            }
          }
        });

        Button cancel = new Button(buttonComp, SWT.PUSH);
        cancel.setText("Cancel");
        cancel.addSelectionListener(new SelectionAdapter() {
          public void widgetSelected(SelectionEvent event) {
            shell.close();
          }
        });
        shell.setDefaultButton(ok);
        
    }
    
    public void disconnectFromServer(IOptionsServer p4d){
        //disconnect from the Perforce server
        try {
			p4d.disconnect();
		} catch (ConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    
    
    public void populatechangelist(String changeLists){
        if (Gui.txt.getText().isEmpty()){
            Gui.txt.setText(Gui.txt.getText() + changeLists);
        } else{
            Gui.txt.setText(Gui.txt.getText() + "\r\n" +  changeLists);
        }
    }
    

    public static void cleanList(List<Integer> changeListsArray, List<StringBuilder> fileListArray, List<String> stateArray, List<String> changeListDescriptionsArray, Table table){
    	changeListsArray.removeAll(changeListsArray);
    	fileListArray.removeAll(fileListArray);
    	stateArray.removeAll(stateArray);
    	changeListDescriptionsArray.removeAll(changeListDescriptionsArray);
    	table.setRedraw(true);
    }
    
}

Open in new window

0
 
LVL 35

Expert Comment

by:mccarl
Comment Utility
Was this last question resolved now, after the new question that I just posted in?

Maybe it is best to get that new one resolved first (the invalid thread access issue) because getting that sorted will affect what (if anything) needs to be done to clear the busy cursor.
0
 

Author Comment

by:Tolgar
Comment Utility
Your response helped me to move forward. I will open a new thread about the busy cursor problem.

Thanks
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

A short article about a problem I had getting the GPS LocationListener working.
Displaying an arrayList in a listView using the default adapter is rarely the best solution. To get full control of your display data, and to be able to refresh it after editing, requires the use of a custom adapter.
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

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

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

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now