Solved

How to sort table items in Java SWT?

Posted on 2013-11-23
7
525 Views
Last Modified: 2013-11-29
Hi,
I am working on creating a GUI using Java SWT and in this GUI I have a table in a dialog box which I populate some results all at once that I read from a database.

Everything worked fine up to this point. Then I wanted to add the sorting feature to this table. Even though I used the same code that I use before for sorting, it does not work in here.

Can you please help me to figure out why this sorting code does not do anything in here even though it seems like the columns are sortable in the GUI with the arrows in the headers?

The first sorting code starts at LINE 323. The second sorting code which is the same as the first one starts at 586.

Note: There is very high and ugly code redundancy and I will change it later but this is how it is now.

The same code is commented out at LINE 661. I tried to use this sorting code in there but it didn't work as well.

This is the entire method: (Sorting codes are at LINES 323, 586 and 661)

    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 
			        + "://" + "some server", 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));
        RowLayout firstRow = new RowLayout();
        //firstRow.spacing = 20;
        Composite workspaceComp = new Composite(shell, SWT.NONE);
        workspaceComp.setLayout(firstRow);
        
        Label label_workspace = new Label(workspaceComp, SWT.NONE);
        label_workspace.setText("Select a workspace:");
        
        RowLayout newRow = new RowLayout();
        newRow.spacing = 20;
        Composite comboComp = new Composite(shell, SWT.NONE);
        comboComp.setLayout(newRow);
            
        final Combo combo_workspaces = new Combo(comboComp, SWT.READ_ONLY);
        combo_workspaces.setEnabled(true);
        
        
        final Button includeSubmitted = new Button(comboComp, SWT.CHECK);
        includeSubmitted.setText("Include submitted changelists");
        
        
        //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();
        final 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", "File(s)"};
        
        //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);
      
      
      
      Composite buttonComp = new Composite(shell, SWT.NONE);
      RowLayout lastRow = new RowLayout();
      lastRow.spacing = 10;
      buttonComp.setLayout(lastRow);
      
      final 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();
          	if (display.isDisposed() || !p4d.isConnected()) return;
              //disconnect from the Perforce server
          	disconnectFromServer(p4d);
          }
        }
      });

      final Button cancel = new Button(buttonComp, SWT.PUSH);
      cancel.setText("Cancel");
      cancel.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent event) {
          shell.close();
        }
      });
      
      
     
      getoptions.setClientName(combo_workspaces.getText());
        //String selectedWorkspace = combo_workspaces.getText();
        //if(eachClientName.contains(selectedWorkspace)){

      
      //Need to combine this listener with the combo listener
      includeSubmitted.addListener(SWT.Selection, new Listener() {
          public void handleEvent(Event event) {
        	if (combo_workspaces.getText().length() > 0){
	      		final String selectedWorkspace = combo_workspaces.getText();	   		
	      		//this is to get the state of the checkbox
	      		final boolean includeSubmittedSelected = includeSubmitted.getSelection();
		        //clear the table
		        table.removeAll();
		        table.setRedraw(true);						            	            	
	          	Runnable longJob = new Runnable() {
	          	boolean done = false;       
	          	int id;
					@Override
					public void run() {
						Thread thread = new Thread(new Runnable() {
							@Override
							public void run() {         


				        	if (display.isDisposed() || table.isDisposed()) return;
								display.syncExec(new Runnable() {
									@Override
									public void run() {
										if (combo_workspaces.getText().length() > 0){
											groupTable.setText("Processing...");
											includeSubmitted.setEnabled(false);
										}
									}
								});
								
//								display.syncExec(new Runnable() {
//									@Override
//									public void run() {
							        	for (String changelistState : changelistStateArray){
							        		
//							                getoptions.setClientName(combo_workspaces.getText());
							        		getoptions.setClientName(selectedWorkspace);
							                
							                if (changelistState.equalsIgnoreCase("Pending")){
							                	getoptions.setType(IChangelist.Type.PENDING);
							                } else if (changelistState.equalsIgnoreCase("Shelved")){
							                	getoptions.setType(IChangelist.Type.SHELVED);
							                } else if(changelistState.equalsIgnoreCase("Submitted") && includeSubmittedSelected){
							                	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);
							                    	//DEBUG:: System.out.println(eachChangeList.getId()+" - " + eachChangeList.getDescription());
							                    		
							                        IChangelist cinfo = null;
													try {
														if (display.isDisposed() || !p4d.isConnected()) return;
														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 {
														if (display.isDisposed() || !p4d.isConnected()) return;
														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 {
							                        	if (display.isDisposed() || !p4d.isConnected()) return;
														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){
							                            //DEBUG:: System.out.println(eachFileSpec.getDepotPathString());
							                            String lineFeed = System.getProperty("line.separator");
							                            if (eachFileSpec.getDepotPathString() != null){
							                            	depotfiles = depotfiles.append(eachFileSpec.getDepotPathString() + ", ");
							                            } else{
							                            	depotfiles = depotfiles.append(eachFileSpec.getLocalPathString() + ", ");
							                            }
							                        }    
							                        fileListArray.add(depotfiles);
							                    }
							        		}
//									}
//								});
							        	if (display.isDisposed() || table.isDisposed()) return;
										display.syncExec(new Runnable() {
											@Override
											public void run() {
								            //This is to populate data in the table
								            for (int loopIndex = 0; loopIndex < changeListsArray.size(); loopIndex++) {
								            	if(fileListArray.get(loopIndex).toString().length() > 0){
								            	  TableItem item = new TableItem(table, SWT.NULL);
								            	  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));
								                }else{
								            	  //do not show changelist which does not have file in it.
								              }
								            }
								            
								            for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
								            	table.getColumn(loopIndex).pack();
								            }
								            
							            
							            table.setRedraw(true);
											}
										});
										
										
							        	if (display.isDisposed() || table.isDisposed()) return;
										display.syncExec(new Runnable() {
											@Override
											public void run() {
												if (table.getItemCount() > 0 && combo_workspaces.getText().length() > 0){
													groupTable.setText("Completed");
													includeSubmitted.setEnabled(true);
												} else if (!(combo_workspaces.getText().length() > 0)){
													groupTable.setText("Please select a workspace");
													includeSubmitted.setEnabled(true);
												} else{
													groupTable.setText("...No changelists");
													includeSubmitted.setEnabled(true);
												}
											}
										});
										

										
								        final boolean processCompleted = true;
							            //clears the table
							            //cleanList(changeListsArray, fileListArray, stateArray, changeListDescriptionsArray, table);
								        cleanList(changeListsArray, fileListArray, stateArray, table);
							            
							            
							            if (display.isDisposed() || !p4d.isConnected()) return;
										display.syncExec(new Runnable() {
											@Override
											public void run() {
												if (processCompleted){
												//text.append("\nCompleted long running task "+id);
												//System.out.println("Completed long running task");
												}else{
													return;
												}
											}
										});
										done = true;
										display.wake();
							            
										display.syncExec(new Runnable() {
											@Override
											public void run() {
										        //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);	
												}
											});
//										}
//									});	//sync.exec				        					        					            
								} //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);
					
					//I tried the following code to change the busy indicator style based on cursor location 
//					if (display.isDisposed() || table.isDisposed()) {
//						return;
//					}else{
//						ok.setCursor(display.getSystemCursor(SWT.CURSOR_ARROW));
//						cancel.setCursor(display.getSystemCursor(SWT.CURSOR_ARROW));
//					}
          	} else{ 
    			groupTable.setText("Please select a workspace");
    		} //if combo is selected//if combo selected
          } //widgetSelected
      });
      
      
        combo_workspaces.addSelectionListener(new SelectionAdapter() {
        	@Override
            public void widgetSelected(SelectionEvent e) {
        		if (combo_workspaces.getText().length() > 0){
	        		final String selectedWorkspace = combo_workspaces.getText();	       		
	        		//this is to get the state of the checkbox
	        		final boolean includeSubmittedSelected = includeSubmitted.getSelection();
			        //clear the table
			        table.removeAll();
			        table.setRedraw(true);						            	            	
	            	Runnable longJob = new Runnable() {
	            	boolean done = false;       
	            	int id;
					@Override
					public void run() {
						Thread thread = new Thread(new Runnable() {
							@Override
							public void run() {         


					        	if (display.isDisposed() || table.isDisposed()) return;
									display.syncExec(new Runnable() {
										@Override
										public void run() {
											if (combo_workspaces.getText().length() > 0){
												groupTable.setText("Processing...");
												includeSubmitted.setEnabled(false);
											}
										}
									});
								
//								display.syncExec(new Runnable() {
//									@Override
//									public void run() {
							        	for (String changelistState : changelistStateArray){
							        		
//							                getoptions.setClientName(combo_workspaces.getText());
							        		getoptions.setClientName(selectedWorkspace);
							                
							                if (changelistState.equalsIgnoreCase("Pending")){
							                	getoptions.setType(IChangelist.Type.PENDING);
							                } else if (changelistState.equalsIgnoreCase("Shelved")){
							                	getoptions.setType(IChangelist.Type.SHELVED);
							                } else if(changelistState.equalsIgnoreCase("Submitted") && includeSubmittedSelected){
							                	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);
							                    	//DEBUG:: System.out.println(eachChangeList.getId()+" - " + eachChangeList.getDescription());
							                    		
							                        IChangelist cinfo = null;
													try {
														if (display.isDisposed() || !p4d.isConnected()) return;
														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 {
														if (display.isDisposed() || !p4d.isConnected()) return;
														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 {
							                        	if (display.isDisposed() || !p4d.isConnected()) return;
														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){
							                            //DEBUG:: System.out.println(eachFileSpec.getDepotPathString());
							                            String lineFeed = System.getProperty("line.separator");
							                            if (eachFileSpec.getDepotPathString() != null){
							                            	depotfiles = depotfiles.append(eachFileSpec.getDepotPathString() + ", ");
							                            } else{
							                            	depotfiles = depotfiles.append(eachFileSpec.getLocalPathString() + ", ");
							                            }
							                        }    
							                        fileListArray.add(depotfiles);
							                    }
							        		}
//									}
//								});
							        	if (display.isDisposed() || table.isDisposed()) return;
										display.syncExec(new Runnable() {
											@Override
											public void run() {
								            //This is to populate data in the table
								            for (int loopIndex = 0; loopIndex < changeListsArray.size(); loopIndex++) {
								            	if(fileListArray.get(loopIndex).toString().length() > 0){
								            	  TableItem item = new TableItem(table, SWT.NULL);
								            	  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));
								                }else{
								            	  //do not show changelist which does not have file in it.
								              }
								            }
								            
								            for (int loopIndex = 0; loopIndex < titles.length; loopIndex++) {
								            	table.getColumn(loopIndex).pack();
								            }
								            
							            
							            table.setRedraw(true);
											}
										});
										
										
							        	if (display.isDisposed() || table.isDisposed()) return;
										display.syncExec(new Runnable() {
											@Override
											public void run() {
												if (table.getItemCount() > 0 && combo_workspaces.getText().length() > 0){
													groupTable.setText("Completed");
													includeSubmitted.setEnabled(true);
												} else if (!(combo_workspaces.getText().length() > 0)){
													groupTable.setText("Please select a workspace");
													includeSubmitted.setEnabled(true);
												} else{
													groupTable.setText("...No changelists");
													includeSubmitted.setEnabled(true);
												}
											}
										});
										

										
								        final boolean processCompleted = true;
							            //clears the table
							            //cleanList(changeListsArray, fileListArray, stateArray, changeListDescriptionsArray, table);
								        cleanList(changeListsArray, fileListArray, stateArray, table);
							            
							            
							            if (display.isDisposed() || !p4d.isConnected()) return;
										display.syncExec(new Runnable() {
											@Override
											public void run() {
												if (processCompleted){
												//text.append("\nCompleted long running task "+id);
												//System.out.println("Completed long running task");
												}else{
													return;
												}
											}
										});
										done = true;
										display.wake();
							            
										display.syncExec(new Runnable() {
											@Override
											public void run() {
										        //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);	
												}
											});
//										}
//									});	//sync.exec				        					        					            
								} //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);
					
					//I tried the following code to change the busy indicator style based on cursor location 
//					if (display.isDisposed() || table.isDisposed()) {
//						return;
//					}else{
//						ok.setCursor(display.getSystemCursor(SWT.CURSOR_ARROW));
//						cancel.setCursor(display.getSystemCursor(SWT.CURSOR_ARROW));
//					}
        		} else{ 
        			groupTable.setText("Please select a workspace");
        		} //if combo is selected
            } //widgetSelected  
          }); //SelectionAdapter
        
		
        //Sort does not work in the changelist dialog. Revisit this part later.
//		display.syncExec(new Runnable() {
//			@Override
//			public void run() {
//		        //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);	
//				}
//			});
        
        
   
				        
        //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();
                    String fileFromChangelist = "-c " + current.getText(2) + " -" + current.getText(1).toLowerCase();
                    if(current.getChecked())
                    {           
                    	if (changelistNum.isEmpty()){
                    		changelistNum = fileFromChangelist;
                    	}else{
                    		changelistNum = changelistNum + lineFeed + fileFromChangelist;
                    	}
                        //DEBUG:: System.out.println(current.getText(2));
                    } else{
                    	String removeIt = fileFromChangelist; //remove the changelist from the list if it is unchecked
                    	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();
//            	if (display.isDisposed() || !p4d.isConnected()) return;
//                //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);
        
    }   

Open in new window

0
Comment
Question by:Tolgar
  • 3
  • 3
7 Comments
 
LVL 26

Expert Comment

by:dpearson
ID: 39672255
I'd like to try to help - but as best as I can see this is about 700 lines of code in a single createContents() method.

I know you mentioned that it needed some reworking but I'm afraid that current code is too complicated for me to figure out (and I've been a professional developer for about 20 years now).  I'd suggest breaking the code up into some smaller pieces - just so it's easier to wrap your mind around.

For example when you do this sort of thing:

            includeSubmitted.addListener(SWT.Selection, new Listener() {
                  public void handleEvent(Event event) {
                                  // lots of code
                        }

It may be better to do this instead -

private static class MyListener implements Listener() {
      private final Table table ;
      public MyListener(Table myTable) {
           table = myTable ;
      }

      public void handleEvent(Event event) {
           // Lots of code
      }
}

so that now you get this code in the main method:
            includeSubmitted.addListener(SWT.Selection, new MyListener(table)) ;

I know you may think this doesn't get your table sorted - but it should only take about 20 mins to break all of the anonymous methods/classes into separate pieces and then the resulting code will be much easier to understand and debug.

You may even find your bug as a result of doing this.  Right now it's very hard to know what code is modifying the 'table' object - this will make that more obvious.

What's more - I bet you'll find more experts able to help then.

Just my 2 cents,

Doug
0
 

Author Comment

by:Tolgar
ID: 39672261
I see your point but I am not very clear about how your suggestion will work. Can you please be more specific about your suggestion? Can you show me one example using my code?

Thanks,
0
 
LVL 26

Accepted Solution

by:
dpearson earned 250 total points
ID: 39672869
Tolgar the code I posted was taken from your code.  You should be able to take what I wrote and copy it directly into your file.

The part where I wrote "lots of code" would start at line 138 in your original file.

So the steps would be:
a) Add a new private static class (I called my example MyListener)
b) Copy your existing "handleEvent" method code into the new class
c) Make sure that you are passing in enough variables (like 'table') to the new class so that the handleEvent method compiles.

If you really get stuck let me know and I'll take a pass at doing this for you.

Doug
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:Tolgar
ID: 39672975
Hi Doug,
I am really not familiar with this. I messed up after a few trials.

I would really appreciate, if you could do this for me.

Thanks,
0
 
LVL 26

Expert Comment

by:dpearson
ID: 39673695
Yeah it looks like I was mistaken.  I tried to re-organize the code but it's incredibly tangled.  All of the anonymous classes are referring directly to a huge list of other variables and methods, some of which are declared locally and others of which aren't even here.

It's just too complicated for me to figure out what this is doing.

I'm sorry I can't be more helpful - this code is just too complex for me.  Ironically that's one of the skills that you will develop as you get more experience is learning how to write code in a way that is simpler.  But writing "simple" code is harder than writing complicated code (if only that weren't true) and I can't see what is going on here well enough to help you.

Maybe another expert can figure this out.

Sorry,

Doug
0
 

Author Comment

by:Tolgar
ID: 39673735
I see.

@mccarl: you are more familiar with this code. Do you have any idea what is wrong in here?
0
 
LVL 35

Assisted Solution

by:mccarl
mccarl earned 250 total points
ID: 39676293
I wholeheartedly agree with Doug, there is just no way to make sense of all of that in the current state.

I do have an idea of what is going wrong here though. I think it's going wrong because of all the threading/display.syncExec stuff that you are trying to do. There is just WAY TOO MANY display.syncExec calls in that code!!!!!! And I guess this stems from when you tried to make your code run in a separate thread, you got invalid thread access exceptions. Then you simply tried to put display.syncExec calls around those lines that caused the exceptions. Am I close?

You generally should only have 1 display.syncExec (or asyncExec) call per thread that you are starting. Now that is not a hard constraint that must always be met, but just a guideline for you to trigger a "Am I using it too much" rethink if you do see it used more than once. I tried to provide you a couple 'rules' to using it in one of your other questions, let me try to rephrase that here...

If you are calling GUI methods before your long running operations, ie. at the start of the (new) thread, then move those out of the thread to just before you start the new thread. eg. lines 159 - 162 of the above. Otherwise, if you have multiple display.syncExec calls one directly after the other, just combine that code all into the one call.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

A short article about a problem I had getting the GPS LocationListener working.
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

757 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

22 Experts available now in Live!

Get 1:1 Help Now