Solved

How to put data in a table and in a drop down menu from a List in JAVA?

Posted on 2013-11-13
11
273 Views
Last Modified: 2013-11-14
Hi,
I am working on a GUI in Java. I have a button which opens a dialog box and in this dialog box I want to populate some information that I read from a server.

In terms of getting information from the server, I have no problem.

But I am not very clear how I can populate this information which is stored in different Lists in this dialog box.

I am sending the code below: (I commented out the server communication part to help you easily generate the dialog box in your system). The code below will show some static data. Now, I want to change this static data with the actual data that I get from the server.

The static data will be replaced as the following (the list information that I get from the server):

workspace name will be eachChangeSummary.getName()
changelist will be eachChangeList.getId()
description will be eachChangeList.getDescription()

State and Files columns in the table can stay static for now.

I marked the parts of the code that needs to be changed as "//THE FOLLOWING LINES SHOULD CHANGE TO POPULATE DATA FROM THE SERVER". (Lines 160 and 179)

The rest of the code should not need a change.

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 change list");
        createContents(shell);
                
        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 );
        
        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) {
    	
    	//Connect to Perforce Server
    	IOptionsServer p4d = null;
		try {
			p4d = ServerFactory.getOptionsServer(
			        ServerFactory.DEFAULT_PROTOCOL_NAME 
			        + "://" + "someserver", null);
			
			p4d.setUserName("somename");			
		} catch (ConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchObjectException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ConfigException 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();
		}

        
        try {
			p4d.connect();
		} 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();
		}
        
//        //Get the workspace and changelist information from Perforce
//        List<IClientSummary> clientSummaryList = getAllPerforceWorkspaces(p4d);
                
        shell.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_user = new Label(shell, SWT.NONE);
        label_user.setText("User:");
        GridData data_user = new GridData();
        label_user.setLayoutData(data_user);
        
        Label label_workspace = new Label(shell, SWT.NONE);
        label_workspace.setText("Workspace:");
        GridData data_workspace = new GridData();
        label_workspace.setLayoutData(data_workspace);
        
        final Text text_user = new Text(shell, SWT.BORDER);
        GridData data_textUser = new GridData(GridData.FILL_HORIZONTAL);
        text_user.setLayoutData(data_textUser);
        
        final Combo combo_workspaces = new Combo(shell, SWT.READ_ONLY);
        
//        //This is to create the data(changelist number, file name, description) in each column using P4JAVA
//        GetChangelistsOptions getoptions = new GetChangelistsOptions();
//        //getoptions.setType(IChangelist.Type.SUBMITTED);
//        for(IClientSummary eachChangeSummary : clientSummaryList){
//            String eachClientName = eachChangeSummary.getName();
//            if(eachClientName.contains("tolgar")){
//                getoptions.setClientName(eachClientName);
//                List<IChangelistSummary> changeLists = null;
//				try {
//					changeLists = p4d.getChangelists(null, getoptions);
//				} catch (P4JavaException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//                System.out.println(eachChangeSummary.getName() +" : "+eachChangeSummary.getDescription() );
//                    for(IChangelistSummary eachChangeList : changeLists){
//                        System.out.println(eachChangeList.getId()+" - "+eachChangeList.getDescription());
//                    }
//            }
//        }
               
         //THE FOLLOWING LINES SHOULD CHANGE TO POPULATE DATA FROM THE SERVER
        //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);
        GridData data_comboWorkspaces = new GridData(GridData.FILL_HORIZONTAL);
        combo_workspaces.setLayoutData(data_comboWorkspaces);

        // ----------- the table -----------------
        Table table = new Table(shell, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
        table.setHeaderVisible(true);
        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]);
        }
                           
      //THE FOLLOWING LINES SHOULD CHANGE TO POPULATE DATA FROM THE SERVER 
      for (int loopIndex = 0; loopIndex < 20; loopIndex++) {
        TableItem item = new TableItem(table, SWT.NULL);
        item.setText(0, "PENDING");
        item.setText(1, "change list " + loopIndex);
        item.setText(2, "" + 2 * loopIndex);
        item.setText(3, "change list description : " + 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();
      }
          
        GridData data3 = new GridData(GridData.FILL_HORIZONTAL);
        data3.horizontalSpan = 2;
        table.setLayoutData(data3);
        
        // ----------- third row -----------------
        Button ok = new Button(shell, 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();	            
            }else{
            	shell.close();
            }
          }
        });

        Button cancel = new Button(shell, 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);
        
//        //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);
        }
    }
}

Open in new window


How should I change the code above, so that the workspace drop down list and part of the table populate the data from the information that I get from the server?

Thanks,
0
Comment
Question by:Tolgar
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 2
11 Comments
 
LVL 36

Accepted Solution

by:
mccarl earned 500 total points
ID: 39646591
Ok, so you just need to create and populate some ArrayList's to hold your information when you retrieve it from the server. So, on line 138 of the above, add something like...
List<String> workspaces = new ArrayList<String>();
List<String> changeLists = new ArrayList<String>();
List<String> changeListDescriptions = new ArrayList<String>();

Open in new window

And then in the clientSummaryList loop (line 143,144) add....
workspaces.add(eachChangeSummary.getName());

Open in new window

and in the changeLists loop (line 155) add....
changeLists.add(eachChangeList.getId());
changeListDescriptions.add(eachChangeList.getDescription());

Open in new window



So, now you have all the data that you need in those structures, the rest is easy. On line 164, replace combo_workspaces.setItems(items);  with...
combo_workspaces.setItems(workspaces.toArray(new String[workspaces.size()]));

Open in new window


And on line 180, replace the value  20  with  changeLists.size()  then in the loop you can do...
item.setText(1, changeLists.get(loopIndex));
...
item.setText(3, changeListDescriptions.get(loopIndex));

Open in new window

0
 

Author Comment

by:Tolgar
ID: 39646906
I tried it but there is a slight problem:

changeLists.add(eachChangeList.getId());

reports an error. It says "The method add(int, String) in the type List<String> is not applicable for the arguments (int)"

I tried to change it to addAll but it didn't help.

Do you have any idea?
0
 

Author Comment

by:Tolgar
ID: 39646913
I did this:

changeLists.add(eachChangeList.getId(), null);

Open in new window


Would this cause a bug later on?
0
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 

Author Comment

by:Tolgar
ID: 39646926
@mccarl: Actually, I got an error for the line below:

changeListsArray.add(eachChangeList.getId(), null);

Open in new window


The error says:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 437231, Size: 0
0
 

Author Comment

by:Tolgar
ID: 39646938
@mccarl: I would like to mention that I changed the variables names you sent me due to name clashes as the following:
List<String> workspacesArray = new ArrayList<String>();
List<String> changeListsArray = new ArrayList<String>();
List<String> changeListDescriptionsArray = new ArrayList<String>();

Open in new window

0
 

Author Comment

by:Tolgar
ID: 39646956
ok. I made this change and it did solve this problem:

List<Integer> changeListsArray = new ArrayList<Integer>();

Open in new window


and

item.setText(1, changeListsArray.get(loopIndex).toString());

Open in new window


The works fine but the problem is I do not see any workspace (client) names in the drop down menu.

Do you have any idea about it? Why don't they show up?
0
 

Author Comment

by:Tolgar
ID: 39646986
@mccarl: My bad. I made a mistake. Now it works as expected.

I have two more questions about the same code. But I will open two separate questions for them because they deserve to be separate question due to their complexity.

Then I will close this one.

Thanks a lot again!
0
 
LVL 36

Expert Comment

by:mccarl
ID: 39646994
I've only just seen all your comments, but it looks like you have been able to sort the rest out yourself, good work! And yes, what you ended up with would be the way to go. I hadn't checked the javadoc to see what the data types were, I just assumed they were all String. :)
0
 

Author Comment

by:Tolgar
ID: 39647023
Thanks :)

I just opened another related with the same code snippet.

Can you please take a look at it?

http://www.experts-exchange.com/Programming/Languages/Java/Q_28293793.html
0
 

Author Comment

by:Tolgar
ID: 39647057
And I also created this question:

http://www.experts-exchange.com/Programming/Languages/Java/Q_28293801.html

I would appreciate if you could take a look at it.

Thanks,
0
 

Author Closing Comment

by:Tolgar
ID: 39648638
Perfect solution!
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Displaying an arrayList in a listView using the default adapter is rarely the best solution. To get full control of your display data, and to be able to refresh it after editing, requires the use of a custom adapter.
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
This video teaches viewers about errors in exception handling.
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

728 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