473,396 Members | 1,789 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,396 developers and data experts.

Auto completion in SWT Text Field

DebadattaMishra
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, 1185 views)
Dec 29 '09 #1
1 19776
RedSon
5,000 Expert 4TB
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

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: porterboy | last post by:
Hi Folks, I have auto-completion set up in my python interpreter so that if I hit the tab key it will complete a variable or a python command*. eg. if I type >>> imp and if I then hit the tab...
1
by: JLuppens | last post by:
Does anyone know if there is a way to track changes in a text field like word does? I am using a SQL2000 database and can use either VB.Net or Access. The field is either ntext or Varchar. I...
4
by: mitch-co2 | last post by:
What I am trying to do is when someone clicks on the YES radio button I want the text field called MYTEXT to equal the text field named DATE. The below code works as long as I do NOT UN-COMMENT...
1
by: Roshan | last post by:
Hi All, I am developing an xml editor, inwhich I want to include text auto-completion. When I finish entering start element (ie.<Hello>) on rich text box, the end element (ie.</Hello>) should...
4
by: Ben Fidge | last post by:
How would I disable IE auto completion on text boxes that receive credit card information? I'd like to continue using standard built-in TextBox server controls if possible. Kind regards Ben
8
by: John | last post by:
Hi I need a auto-number field but with a letter prefix like "P1", "P2" etc. What is the way to achieve this? Is it possible to do this at table level? Thanks Regards
1
by: Michael2767 | last post by:
I need an auto counting text field on a form. I need it to count from 0001 to unlimited in a years time for the number of records created, then start over at 0001 when the years time has elapsed. ...
5
greeni91
by: greeni91 | last post by:
Hi All, I am currently upgrading a problem report I did a little while back and my boss asked if I could: Auto Complete "Completion Date" field with today's date Grey out a select amount of...
2
by: MOCaseA | last post by:
OK I have a problem. I'm fairly sure this has been answered somewhere, but ai can't seem to find it. I have a single table with 3 fields: Table1: empFirstName empLastName empFullName In a...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.