473,761 Members | 4,407 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Auto completion in SWT Text Field

DebadattaMishra
1 New Member
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 ContentProposal Adapter to that text field. There is a class callec "SimpleContentP roposalProvider " 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 SimpleContentPr oposalProvider by passing the array of proposals
as new SimpleContentPr oposalProvider( allProposals );
3. Form the key sequence so that by pressing key sequence, the proposal list will appear
as KeyStroke.getIn stance("CTRL+Sp ace");
4. Finally attach the "ContentProposa lAdapter" to the text field as
new ContentProposal Adapter( SWT Text field, new TextContentAdap ter(),SimpleCon tentProposalAda pter,Key sequence,null) etc.


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

Code for AutoCompletionT extField.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, 1187 views)
Dec 29 '09 #1
1 19818
RedSon
5,000 Recognized Expert Expert
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
2266
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 key, the interpreter will complete it to... >>> import Now, I also use Matlab at the command line a lot and it has a nice
1
2846
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 would like to show users the changes other users have made to a text field using a other font or font color. Thanks
4
4132
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 the NO radio button, once I do that it will not work. Any help would be greatly appreciated. Mitch
1
1790
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 be entered automatically and also the cursor is automatically positioned in between the start element and end element(ie.<Hello>|</Hello>). How should I do this using C# for Windows environment?
4
1817
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
11274
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
3757
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. Please help.
5
3817
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 fields for an ECR Lock feedback field when form has been signed off
2
1491
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 separate Access "DB" I have a form that allows me to create, edit and delete entries on this table. The form has these three text fields:
0
9345
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10115
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9957
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9905
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9775
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5229
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5373
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3881
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2752
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.