Solved

How to filter a drop down list dynamically based on user input in Java?

Posted on 2013-11-13
2
743 Views
Last Modified: 2013-11-20
Hi,
I am working on a GUI in Java. In this GUI, I have a dialog box and in this dialog box I populate some information from a server.

One information is in a drop down menu, the other part of the information is in a table.

I also have a one line text box where I can type some characters in this dialog box.

Now, I want to filter the drop down list as I type something in the text box.

For example, if I have the followings in the drop down menu:

abcd
abcdefg
abcdemn
abcdxyz
wythmn  

Open in new window


And if I type abcde in the text box, I would like to see the followings in the drop down list:

abcdefg
abcdemn

Open in new window


This is the code that I have in order to create the dialog box. I commented out the part that has calls to the server to make it easier for you to create the dialog box in your system:

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


Can you please help me in filtering this list based on user input?
0
Comment
Question by:Tolgar
2 Comments
 

Author Comment

by:Tolgar
ID: 39648031
Update: I am changing the question  little bit. Instead of using the separate text box, I would prefer to do the filtering in the drop down list. It seems more straightforward.

For example, If I type "k" now after I open the drop down list, the drop down list goes to the beginning of the rows that the line that starts with "k". I think this is a default behavior because I didn't do anything to have this feature. However, the missing part is, if I keep typing other letter it always takes the last letter I type as the first letter in the list.

For example, after I type "k", if I keep typing "ka", it goes to the beginning of the rows that the lines start with "a".

What I expect is:

If I type "ka" I expect to go to the beginning of the rows that the line starts with "ka". Or if I keep typing "kampo", I expect to go the beginning of the rows that the lines starts with "kampo". If the list does not have any rows that starts with "kampo", but if the list has a row that starts with "kamp", it should go to the beginning of the rows that the line starts with "kamp".

I think this is a very typical filtering mechanism. Can you please let me know how I can do it?

Example case:


This is the drop down list:

john.car.home
john.car.bike
john.car.plane
jeff.car.park
john.home.car
tim.bike.car

Open in new window


After I open the drop down list, I see the list above and I type the following:

john.car.p

Open in new window


Expected location:
john.car.plane

Open in new window


If I keep typing the following:

john.car.pa

Open in new window


Expected location:
john.car.park

Open in new window


After a while, if I type the following:
jenny

Open in new window


Expected location is:
jeff.car.park

Open in new window



Thanks,
0
 
LVL 35

Accepted Solution

by:
girionis earned 500 total points
ID: 39651175
What you need is called "auto-completion". Here is a tutorial on how to do it in SWT.
0

Featured Post

How to run any project with ease

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

Join & Write a Comment

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.
If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This video teaches viewers about errors in exception handling.

758 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

20 Experts available now in Live!

Get 1:1 Help Now