By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,846 Members | 1,514 Online
Bytes IT Community
Submit an Article
Got Smarts?
Share your bits of IT knowledge by writing an article on Bytes.

Auto completion in SWT Text Field

DebadattaMishra
P: 1
Introduction
In case of rich applications, you must have observed that a text field behaves like a dynamic combo box. When the user enters some characters in the text field, a popup will come up with a list of values as suggestions to the user. This feature is called auto completion. In case of Eclipse editor, you must have
seen while writing java code, if the developers presses "Ctrl+Space" a dynamic list box come up with multiple suggestions. So in this article, I will show you how you can achieve this feature while working on eclipse plugin development.

Technicalities
The concept is very simple here as Eclipse provides all the features for this. First of all, create a text field and attach ContentProposalAdapter to that text field. There is a class callec "SimpleContentProposalProvider" which takes
an array of Strings as proposals to the users. Besides you have to form a key sequence, based upon which the all the proposals will come up as s list. Let me give me a snnippet for you.

1. Get all the proposals as String array.
String[] allProposals = {"a","b","c"}; etc
2. Create an object of SimpleContentProposalProvider by passing the array of proposals
as new SimpleContentProposalProvider( allProposals );
3. Form the key sequence so that by pressing key sequence, the proposal list will appear
as KeyStroke.getInstance("CTRL+Space");
4. Finally attach the "ContentProposalAdapter" to the text field as
new ContentProposalAdapter( SWT Text field, new TextContentAdapter(),SimpleContentProposalAdapter, Key sequence,null) etc.


Now let us have complete code structure so that you can get the full picture.

Code for AutoCompletionTextField.java

Expand|Select|Wrap|Line Numbers
  1. package com.core.plugin.text;
  2.  
  3. import org.eclipse.jface.bindings.keys.KeyStroke;
  4. import org.eclipse.jface.fieldassist.ContentProposalAdapter;
  5. import org.eclipse.jface.fieldassist.SimpleContentProposalProvider;
  6. import org.eclipse.jface.fieldassist.TextContentAdapter;
  7. import org.eclipse.swt.SWT;
  8. import org.eclipse.swt.events.KeyAdapter;
  9. import org.eclipse.swt.events.KeyEvent;
  10. import org.eclipse.swt.layout.FormAttachment;
  11. import org.eclipse.swt.layout.FormData;
  12. import org.eclipse.swt.layout.FormLayout;
  13. import org.eclipse.swt.widgets.Display;
  14. import org.eclipse.swt.widgets.Label;
  15. import org.eclipse.swt.widgets.Shell;
  16. import org.eclipse.swt.widgets.Text;
  17.  
  18. /**
  19.  * This class is used to ptovide an example of showing
  20.  * completion feature in a text field.
  21.  * @author Debadatta Mishra(PIKU)
  22.  *
  23.  */
  24. public class AutoCompletionTextField 
  25. {
  26.     /**
  27.      * A label for for display of message.
  28.      */
  29.     private static Label label = null;
  30.     /**
  31.      * Object of type {@link Text} to display a text field
  32.      */
  33.     private static Text text = null;
  34.     /**
  35.      * A String array of default proposals for autocompletion
  36.      */
  37.     private static String[] defaultProposals = new String[] { "Assistance 1","Assistance 2", "Assistance 3" , "Assistance 4" , "Assistance 5"};
  38.     /**
  39.      * A String for key press
  40.      */
  41.     private static String KEY_PRESS = "Ctrl+Space";
  42.  
  43.     /**
  44.      * Method used to create a label.
  45.      * 
  46.      * @author Debadatta Mishra (PIKU)
  47.      * @param shell of type {@link Shell}
  48.      */
  49.     private static void createLabel( Shell shell )
  50.     {
  51.         label = new Label( shell , SWT.NONE);
  52.         label.setText("Enter some text in the text field");
  53.         //Alignment of label in the shell
  54.         FormData label1LData = new FormData();
  55.         label1LData.width = 162;
  56.         label1LData.height = 15;
  57.         label1LData.left =  new FormAttachment(0, 1000, 12);
  58.         label1LData.top =  new FormAttachment(0, 1000, 12);
  59.         label.setLayoutData(label1LData);
  60.     }
  61.  
  62.     /**
  63.      * Method used to display an array of String data for
  64.      * autocompletion. You can have your own method like
  65.      * this to get the autocompletion data. This method
  66.      * can be customized to get the data from database
  67.      * and you can display as autocompletion array.
  68.      * 
  69.      * @param text of type String
  70.      * @return an array of String data
  71.      * @author Debadatta Mishra (PIKU)
  72.      */
  73.     private static String[] getAllProposals( String text )
  74.     {
  75.         String[] proposals = new String[5];
  76.         if( text == null || text.length() == 0 )
  77.             proposals = defaultProposals;
  78.         else
  79.         {
  80.             for( int i = 0 ; i < 5 ; i++ )
  81.                 proposals[i] = text+i;
  82.         }
  83.         return proposals;
  84.     }
  85.  
  86.     /**
  87.      * This method is used to provide the implementaion
  88.      * of eclipse autocompletion feature. User has to press
  89.      * "CTRL+Space" to see the autocompletion effect.
  90.      * 
  91.      * @param text of type {@link Text}
  92.      * @param value of type String
  93.      * @author Debadatta Mishra (PIKU)
  94.      */
  95.     private static void setAutoCompletion( Text text , String value )
  96.     {
  97.         try
  98.         {
  99.             ContentProposalAdapter adapter = null;
  100.             String[] defaultProposals = getAllProposals(value);
  101.             SimpleContentProposalProvider scp = new SimpleContentProposalProvider( defaultProposals );
  102.             scp.setProposals(defaultProposals);
  103.             KeyStroke ks = KeyStroke.getInstance(KEY_PRESS);
  104.             adapter = new ContentProposalAdapter(text, new TextContentAdapter(),
  105.                     scp,ks,null);
  106.             adapter.setProposalAcceptanceStyle(ContentProposalAdapter.PROPOSAL_REPLACE);
  107.         }
  108.         catch( Exception e )
  109.         {
  110.             e.printStackTrace();
  111.         }
  112.     }
  113.  
  114.     /**
  115.      * Method used to create a text field.
  116.      * 
  117.      * @author Debadatta Mishra (PIKU)
  118.      * @param shell of type {@link Shell}
  119.      * @author Debadatta Mishra (PIKU)
  120.      */
  121.     private static void createText( Shell shell )
  122.     {
  123.         text = new Text(shell,SWT.BORDER);
  124.         //Alignment of Text field in the shell
  125.         FormData text1LData = new FormData();
  126.         text1LData.width = 223;
  127.         text1LData.height = 34;
  128.         text1LData.left =  new FormAttachment(0, 1000, 236);
  129.         text1LData.top =  new FormAttachment(0, 1000, 12);
  130.         text.setLayoutData(text1LData);
  131.         //Method for autocompletion
  132.         setAutoCompletion(text, null);
  133.  
  134.         text.addKeyListener( new KeyAdapter()
  135.         {
  136.             public void keyReleased(KeyEvent ke) 
  137.             {
  138.                 //Method for autocompletion
  139.                 setAutoCompletion(text, text.getText());
  140.             }
  141.         }
  142.         );
  143.     }
  144.  
  145.     /**
  146.      * Main method to execute the test
  147.      * 
  148.      * @author Debadatta Mishra (PIKU)
  149.      * @param args of type {@link String}
  150.      */
  151.     public static void main(String[] args) 
  152.     {
  153.         final Display display = new Display ();
  154.         final Shell shell = new Shell (display, SWT.CLOSE);
  155.         shell.setText("A text field with autocompletion support, press CTRL+Space to see the effect");
  156.         shell.setLayout(new FormLayout());
  157.         shell.setSize(600, 200);
  158.  
  159.         createLabel(shell);
  160.         createText(shell);
  161.  
  162.         shell.open ();
  163.         while (!shell.isDisposed ()) 
  164.         {
  165.             if (!display.readAndDispatch ()) display.sleep ();
  166.         }
  167.         display.dispose ();
  168.     }
  169.  
  170. }
  171.  
You can run the above piece code and press "Ctrl+Space" in the text field to see the effect. You can also download the attahced source code.

Assumptions
I assume that reader of this article has
Exposure to eclipse plugin development
Knowledge on Java language
Knowledge on running programs in Eclipse editor

Test Case details
I have tested the above program in the following conditions.
OS Name : Windows Vista
Eclipse API : 3.2
Java : 1.6.0_16
Java Editor : Eclipse 3.2

Conclusion
I hope that you will enjoy my article. This article does not bear any commercial significance , it is only meant for learning and for novice developers. In case of any problem or errors , feel free to contact me in the email DELETED .
Attached Files
File Type: zip AutoCompletionTextField.zip (1.7 KB, 1094 views)
Dec 29 '09 #1
Share this Article
Share on Google+
1 Comment


RedSon
Expert 5K+
P: 5,000
Thank you for your article. I have to remove your email address since that is not allowed in this forum. We do not want to be the target of spam bots trying to harvest email accounts.

If anyone has any questions they can reply to this post. Or PM you directly, then you can share your email address if you wish with them privately.

-MODERATOR
Jan 5 '10 #2