Solved

How to fix the problem of "cannot refer to a non-final variable table inside an inner class defined in a different method" in Java

Posted on 2013-11-14
9
881 Views
Last Modified: 2013-11-15
Hi,
The problem that I mentioned in the title is about LINE 10 and LINE 28 in the below code.

Change modifier of 'table' to final

However, if I change table to final in LINE 10, then I won't be able to clear the table in LINE 28.

Can you please help me to solve this conflicting problem?

public class ChangeListDlg extends Dialog {

//SOME CODE IN HERE

private void createContents(final Shell shell) {

//SOME CODE IN HERE

        // ----------- the table -----------------
        Table table = new Table(shell, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.WRAP | SWT.MULTI);
        table.setHeaderVisible(true);
        table.getVerticalBar().setVisible(true);
        final String[] titles = { "Checkbox", "State", "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]);
        }
        
        //String selectedWorkspace = combo_workspaces.getText();
        //if(eachClientName.contains(selectedWorkspace)){
        
        combo_workspaces.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) { 
            	
            	//clear the table
            	 table.removeAll();
            	
	        	for (String changelistState : changelistStateArray){
	                getoptions.setClientName(combo_workspaces.getText());
	                
	                if (changelistState.equalsIgnoreCase("Submitted")){
	                	getoptions.setType(IChangelist.Type.SUBMITTED);
	                } else if (changelistState.equalsIgnoreCase("Shelved")){
	                	getoptions.setType(IChangelist.Type.SHELVED);
	                } else if(changelistState.equalsIgnoreCase("Pending")){
	                	getoptions.setType(IChangelist.Type.PENDING);
	                }
	                	                
	                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){
	                    	changeListsArray.add(eachChangeList.getId());
	                    	changeListDescriptionsArray.add(eachChangeList.getDescription());
	                    	stateArray.add(changelistState);
	                    	System.out.println(eachChangeList.getId()+" - "+eachChangeList.getDescription());
	                    }
	        	}
	        	
	        	
	            //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, "file" + 2 * loopIndex);
	              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);
	            
	            Listener sortListener = new Listener() {
	                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;
	                    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) < 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(0).addListener(SWT.Selection, sortListener);
	            table.getColumn(1).addListener(SWT.Selection, sortListener);
	            table.getColumn(2).addListener(SWT.Selection, sortListener);
	            table.setSortColumn(table.getColumn(0));
	            table.setSortDirection(SWT.TOP);
	            
	            table.setRedraw(true);
            }
          });

//SOME CODE IN HERE
}

//SOME CODE IN HERE
}

Open in new window

0
Comment
Question by:Tolgar
  • 5
  • 3
9 Comments
 
LVL 26

Assisted Solution

by:dpearson
dpearson earned 100 total points
ID: 39649078
Looks to me like you should be able to make table final there.

final just means you can't write this:

final Table table = new Table();
table = anotherTable ; // Not allowed - can't change the object that table points to

But you should be fine to do:

final Table table = new Table();
table.removeAll() ;  // Didn't change the object that 'table' is pointing to - just change the contents of the table itself

Have you tried it?  What error do you get?

Doug
0
 

Author Comment

by:Tolgar
ID: 39649359
Well, this does not work.

The only thing that works (which is a terrible solution) is to define the table variable in the class level.

Now, it works but my solution is not a preferred solution.

Does anyone have any idea?
0
 
LVL 26

Expert Comment

by:dpearson
ID: 39649476
Well, this does not work.

Can you say more about what specific error you are getting?
0
 

Author Comment

by:Tolgar
ID: 39649628
I got index out of bounds error.

I am sending the code below with my no-preferred solution: (the server connection part should be commented out to run the code on your system.)

The lines that caused me problem before I applied my solution are LINE 179 and LINE 207.

public class ChangeListDlg extends Dialog {
    
// THIS IS MY SOLUTION 
	public static Table table;
	public static List<Integer> changeListsArray = new ArrayList<Integer>();
	public static List<StringBuilder> fileListArray = new ArrayList<StringBuilder>();
	public static List<String> stateArray = new ArrayList<String>();
	public static List<String> changeListDescriptionsArray = new ArrayList<String>();
// THIS IS THE END OF MY SOLUTION

    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){
                        
            //for getting all the workspaces
            GetClientsOptions clientOptions = new GetClientsOptions();
            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 
			        + "://" + "some_server", null);
			
			p4d.setUserName("tolgar");			

			p4d.connect();
        
    
        //Get the workspace and changelist information from Perforce
        List<IClientSummary> clientSummaryList = getAllPerforceWorkspaces(p4d);
                
        shell.setLayout(new GridLayout(1, true));
        
        GridLayout groupLayoutTwoRows = new GridLayout();
        Group groupTwoRows = new Group(shell, SWT.NONE);       
        groupTwoRows.setLayout(groupLayoutTwoRows);
        GridData firstRowGridData = new GridData(GridData.FILL_BOTH);
        groupTwoRows.setLayoutData(firstRowGridData);
        groupTwoRows.setLayout(new GridLayout(2, true));

//        Label label_submitted = new Label(shell, SWT.NONE);
//        label_submitted.setText("Type changelists");
//        GridData data_submitted = new GridData();
//        data_submitted.horizontalSpan = 2;
//        label_submitted.setLayoutData(data_submitted);
//        
//        final Text text_submittedChangelist = new Text(shell, SWT.BORDER);
//        data_submitted = new GridData(GridData.FILL_HORIZONTAL);
//        data_submitted.horizontalSpan = 2;
//        text_submittedChangelist.setLayoutData(data_submitted);
        // --------- second row -----------------
//        Label label_shelvedPending = new Label(shell, SWT.NONE);
//        label_shelvedPending.setText("Or select changelists by username and workspace:");
//        GridData data_shelvedPending = new GridData();
//        data_shelvedPending.horizontalSpan = 2;
//        label_shelvedPending.setLayoutData(data_shelvedPending);
        
        Label label_submitted = new Label(groupTwoRows, SWT.NONE);
        label_submitted.setText("Type changelists");
        GridData data_submitted = new GridData();
        label_submitted.setLayoutData(data_submitted);
        
        
        Label label_workspace = new Label(groupTwoRows, SWT.NONE);
        label_workspace.setText("Workspace:");
        GridData data_workspace = new GridData();
        label_workspace.setLayoutData(data_workspace);
        
        final Text text_submittedChangelist = new Text(groupTwoRows, SWT.BORDER);
        GridData data_textSubmittedChangelist = new GridData(GridData.FILL_HORIZONTAL);
        text_submittedChangelist.setLayoutData(data_textSubmittedChangelist);
        
        final Combo combo_workspaces = new Combo(groupTwoRows, SWT.READ_ONLY);
        combo_workspaces.setEnabled(true);

        List<String> workspacesArray = new ArrayList<String>();
        final String[] changelistStateArray = {"Submitted", "Shelved", "Pending"};     
        
        //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()]));
        GridData data_comboWorkspaces = new GridData(GridData.FILL_HORIZONTAL);
        combo_workspaces.setLayoutData(data_comboWorkspaces);

        // ----------- the table -----------------
        GridLayout groupLayoutTable = new GridLayout();
        Group groupTable = new Group(shell, SWT.NONE);       
        groupTable.setLayout(groupLayoutTable);
        GridData tableGridData = new GridData(GridData.FILL_BOTH);
        groupTable.setLayoutData(tableGridData);
        groupTable.setLayout(new GridLayout(1, true));
        table = new Table(groupTable, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.WRAP | SWT.MULTI);
        table.setHeaderVisible(true);
        table.getVerticalBar().setVisible(true);
        final String[] titles = { " ", "State", "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();
            	
	        	for (String changelistState : changelistStateArray){
	                getoptions.setClientName(combo_workspaces.getText());
	                
	                if (changelistState.equalsIgnoreCase("Submitted")){
	                	getoptions.setType(IChangelist.Type.SUBMITTED);
	                } else if (changelistState.equalsIgnoreCase("Shelved")){
	                	getoptions.setType(IChangelist.Type.SHELVED);
	                } else if(changelistState.equalsIgnoreCase("Pending")){
	                	getoptions.setType(IChangelist.Type.PENDING);
	                }
	                	                
	                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());
	                            depotfiles = depotfiles.append(eachFileSpec.getDepotPathString());
	                        }    
	                        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);
	            
	            cleanList(changeListsArray, fileListArray, stateArray, changeListDescriptionsArray);
	            
	            Listener sortListener = new Listener() {
	                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;
	                    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) < 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(0).addListener(SWT.Selection, sortListener);
	            table.getColumn(1).addListener(SWT.Selection, sortListener);
	            table.getColumn(2).addListener(SWT.Selection, sortListener);
	            table.setSortColumn(table.getColumn(0));
	            table.setSortDirection(SWT.TOP);
	            
	            table.setRedraw(true);
            }
          });
        //}  
        
                            
        GridData data3 = new GridData(GridData.FILL_HORIZONTAL);
        data3.horizontalSpan = 2;
        table.setLayoutData(data3);
        
        // ----------- third row -----------------
        GridLayout groupLayoutOK = new GridLayout();       
        Group groupOK = new Group(shell, SWT.NONE);       
        groupOK.setLayout(groupLayoutOK);
        GridData OKGridData = new GridData(GridData.FILL_BOTH);
        groupOK.setLayoutData(OKGridData);
        groupOK.setLayout(new GridLayout(2, true));
        
        Button ok = new Button(groupOK, SWT.PUSH);
        ok.setText("Add files from this change list");
        data_submitted = new GridData(GridData.FILL_HORIZONTAL);
        ok.setLayoutData(data_submitted);
        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()){
	            setChangelist(text_submittedChangelist.getText());
	            String changeListNumbers = changelistNum.replaceAll(",", "\r\n-c ");

	            //Replace multiple spaces with once space 
	            changeListNumbers = changeListNumbers.replaceAll(" +", " ");
	            populatechangelist("-c " + changeListNumbers + "\r\n");
	            shell.close();	
	            //disconnect from the Perforce server
	            disconnectFromServer(p4d);
            }else{
            	shell.close();
                //disconnect from the Perforce server
            	disconnectFromServer(p4d);
            }
          }
        });

        Button cancel = new Button(groupOK, SWT.PUSH);
        cancel.setText("Cancel");
        data_submitted = new GridData(GridData.FILL_HORIZONTAL);
        cancel.setLayoutData(data_submitted);
        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){
    	changeListsArray.removeAll(changeListsArray);
    	fileListArray.removeAll(fileListArray);
    	stateArray.removeAll(stateArray);
    	changeListDescriptionsArray.removeAll(changeListDescriptionsArray);
    }
    
}

Open in new window



Thanks,
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 35

Accepted Solution

by:
mccarl earned 400 total points
ID: 39650022
I got index out of bounds error.
Which would have nothing to do with whether your table variable was declared final. For a start, IndexOutOfBounds is an exception that occurs at runtime, nothing to do with compile time issues. Change it back to the other (preferred solution), ie. declare table to be local again, as you originally had it and also add the "final" declaration. And then if you have problems then, post your code and either the full compile time error or the full runtime exception stack trace.
0
 

Author Comment

by:Tolgar
ID: 39650217
Well, I made the change and I don't get  any error now. I think it was due to another problem and I fixed this one as well. But I cannot fully say that it is fixed due to the problem in the table (it is another open question.)

But I have another problem with this code. If you don't mind, I would like to ask this question in here.

The check box that I create in each row is created twice in the same row when I change the selected item in the drop down list. And I keep seeing two instances of  this checkbox after that.

Can you see where I am making the mistake which creates this check box twice?

And also, how can I put another checkbox at the title level of the table so that I can select/unselect all of them?

Please see the full code below:

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.custom.TableEditor;
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 org.eclipse.swt.widgets.Text;

import com.perforce.p4java.client.IClient;
import com.perforce.p4java.client.IClientSummary;
import com.perforce.p4java.core.IChangelist;
import com.perforce.p4java.core.IChangelistSummary;
import com.perforce.p4java.core.file.FileSpecBuilder;
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.IServer;
import com.perforce.p4java.server.ServerFactory;



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){
                        
            //for getting all the workspaces
            GetClientsOptions clientOptions = new GetClientsOptions();
            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();
        
    
        //Get the workspace and changelist information from Perforce
        List<IClientSummary> clientSummaryList = getAllPerforceWorkspaces(p4d);
                
        shell.setLayout(new GridLayout(1, true));
        
        GridLayout groupLayoutTwoRows = new GridLayout();
        Group groupTwoRows = new Group(shell, SWT.NONE);       
        groupTwoRows.setLayout(groupLayoutTwoRows);
        GridData firstRowGridData = new GridData(GridData.FILL_BOTH);
        groupTwoRows.setLayoutData(firstRowGridData);
        groupTwoRows.setLayout(new GridLayout(2, true));

//        Label label_submitted = new Label(shell, SWT.NONE);
//        label_submitted.setText("Type changelists");
//        GridData data_submitted = new GridData();
//        data_submitted.horizontalSpan = 2;
//        label_submitted.setLayoutData(data_submitted);
//        
//        final Text text_submittedChangelist = new Text(shell, SWT.BORDER);
//        data_submitted = new GridData(GridData.FILL_HORIZONTAL);
//        data_submitted.horizontalSpan = 2;
//        text_submittedChangelist.setLayoutData(data_submitted);
        // --------- second row -----------------
//        Label label_shelvedPending = new Label(shell, SWT.NONE);
//        label_shelvedPending.setText("Or select changelists by username and workspace:");
//        GridData data_shelvedPending = new GridData();
//        data_shelvedPending.horizontalSpan = 2;
//        label_shelvedPending.setLayoutData(data_shelvedPending);
        
        Label label_submitted = new Label(groupTwoRows, SWT.NONE);
        label_submitted.setText("Type changelists");
        GridData data_submitted = new GridData();
        label_submitted.setLayoutData(data_submitted);
        
        
        Label label_workspace = new Label(groupTwoRows, SWT.NONE);
        label_workspace.setText("Workspace:");
        GridData data_workspace = new GridData();
        label_workspace.setLayoutData(data_workspace);
        
        final Text text_submittedChangelist = new Text(groupTwoRows, SWT.BORDER);
        GridData data_textSubmittedChangelist = new GridData(GridData.FILL_HORIZONTAL);
        text_submittedChangelist.setLayoutData(data_textSubmittedChangelist);
        
        final Combo combo_workspaces = new Combo(groupTwoRows, 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 = {"Submitted", "Shelved", "Pending"};     
        
        //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()]));
        GridData data_comboWorkspaces = new GridData(GridData.FILL_HORIZONTAL);
        combo_workspaces.setLayoutData(data_comboWorkspaces);

        // ----------- the table -----------------
        GridLayout groupLayoutTable = new GridLayout();
        Group groupTable = new Group(shell, SWT.NONE);       
        groupTable.setLayout(groupLayoutTable);
        GridData tableGridData = new GridData(GridData.FILL_BOTH);
        groupTable.setLayoutData(tableGridData);
        groupTable.setLayout(new GridLayout(1, true));
        
        final Table table = new Table(groupTable, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.WRAP | SWT.MULTI);
        table.setHeaderVisible(true);
        table.getVerticalBar().setVisible(true);
        final String[] titles = { " ", "State", "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();
            	
	        	for (String changelistState : changelistStateArray){
	                getoptions.setClientName(combo_workspaces.getText());
	                
	                if (changelistState.equalsIgnoreCase("Submitted")){
	                	getoptions.setType(IChangelist.Type.SUBMITTED);
	                } else if (changelistState.equalsIgnoreCase("Shelved")){
	                	getoptions.setType(IChangelist.Type.SHELVED);
	                } else if(changelistState.equalsIgnoreCase("Pending")){
	                	getoptions.setType(IChangelist.Type.PENDING);
	                }
	                	                
	                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());
	                            depotfiles = depotfiles.append(eachFileSpec.getDepotPathString());
	                        }    
	                        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);
	            
	            cleanList(changeListsArray, fileListArray, stateArray, changeListDescriptionsArray);
	            
	            Listener sortListener = new Listener() {
	                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;
	                    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) < 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(0).addListener(SWT.Selection, sortListener);
	            table.getColumn(1).addListener(SWT.Selection, sortListener);
	            table.getColumn(2).addListener(SWT.Selection, sortListener);
	            table.setSortColumn(table.getColumn(0));
	            table.setSortDirection(SWT.TOP);
	            
	            table.setRedraw(true);
            }
          });
        //}  
        
                            
        GridData data3 = new GridData(GridData.FILL_HORIZONTAL);
        data3.horizontalSpan = 2;
        table.setLayoutData(data3);
        
        // ----------- third row -----------------
        GridLayout groupLayoutOK = new GridLayout();       
        Group groupOK = new Group(shell, SWT.NONE);       
        groupOK.setLayout(groupLayoutOK);
        GridData OKGridData = new GridData(GridData.FILL_BOTH);
        groupOK.setLayoutData(OKGridData);
        groupOK.setLayout(new GridLayout(2, true));
        
        Button ok = new Button(groupOK, SWT.PUSH);
        ok.setText("Add files from this change list");
        data_submitted = new GridData(GridData.FILL_HORIZONTAL);
        ok.setLayoutData(data_submitted);
        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()){
	            setChangelist(text_submittedChangelist.getText());
	            String changeListNumbers = changelistNum.replaceAll(",", "\r\n-c ");

	            //Replace multiple spaces with once space 
	            changeListNumbers = changeListNumbers.replaceAll(" +", " ");
	            populatechangelist("-c " + changeListNumbers + "\r\n");
	            shell.close();	
	            //disconnect from the Perforce server
	            disconnectFromServer(p4d);
            }else{
            	shell.close();
                //disconnect from the Perforce server
            	disconnectFromServer(p4d);
            }
          }
        });

        Button cancel = new Button(groupOK, SWT.PUSH);
        cancel.setText("Cancel");
        data_submitted = new GridData(GridData.FILL_HORIZONTAL);
        cancel.setLayoutData(data_submitted);
        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){
    	changeListsArray.removeAll(changeListsArray);
    	fileListArray.removeAll(fileListArray);
    	stateArray.removeAll(stateArray);
    	changeListDescriptionsArray.removeAll(changeListDescriptionsArray);
    }
    
}

Open in new window

0
 
LVL 26

Expert Comment

by:dpearson
ID: 39650340
You should try to keep it to one question per topic.  Asking us to do step by step debugging of all the bugs that show up in a program is asking a lot.  Maybe someone else will jump in and volunteer to do that?

Glad you realized that 'final' was indeed OK as we expected.

Doug
0
 

Author Comment

by:Tolgar
ID: 39650362
@mccarl: Do you have any idea what I am doing wrong in here?
0
 

Author Comment

by:Tolgar
ID: 39652806
I solved this problem. Thanks everyone.
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
triangle challenge 4 77
word0 challenge 3 58
Requested array size exceeds VM limit 3 48
maven example error 3 36
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

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

18 Experts available now in Live!

Get 1:1 Help Now