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
269 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
  • 9
  • 2
11 Comments
 
LVL 35

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
Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

 

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 35

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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
session migration servlets 2 36
jdbc error in jsp application 20 46
ejb on wildfly 5 20
Help Required 3 97
A short article about a problem I had getting the GPS LocationListener working.
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

809 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