Text autocomplete , how to implement for each word
This is the code for text auto completed
Hi this code will check only the first entered text any one help me out check each word
ie if we entered "o" the text organization will display after we gave a "space" then enter the "o" again its not displaying the "organization again, any one can help me out
package swing;
import javax.swing.text.*;
import javax.swing.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
publicclass AutoCompleteDocumentextends PlainDocument{
/**
*
*/
privatestaticfinallong serialVersionUID = 1;
private List<String> dictionary =new ArrayList<String>();
private JTextComponent comp;
public AutoCompleteDocument( JTextComponent field, String[] aDictionary ){
comp = field;
dictionary.addAll( Arrays.asList( aDictionary ) );
}
publicvoid addDictionaryEntry( String item ){
dictionary.add( item );
}
publicvoid insertString(int offs, String str, AttributeSet a)
throws BadLocationException{
super.insertString( offs, str, a );
String word = autoComplete( getText( 0, getLength() ) );
if( word !=null ){
super.insertString( offs + str.length(), word, a );
comp.setCaretPosition( offs + str.length() );
comp.moveCaretPosition( getLength() );
}
}
public String autoComplete( String text ){
for( Iterator i = dictionary.iterator(); i.hasNext(); ){
String word = (String) i.next();
if( word.startsWith( text ) ){
return word.substring( text.length() );
}
}
returnnull;
}
/**
* Creates a auto completing JTextField.
*
* @param dictionary an array of words to use when trying auto completion.
* @return a JTextField that is initialized as using an auto
* completing textfield.
*/
publicstatic JTextField createAutoCompleteTextField( String[] dictionary ){
JTextField field =new JTextField();
AutoCompleteDocument doc =new AutoCompleteDocument( field,dictionary );
field.setDocument(doc);
return field;
}
//field.addKeyListener(new java.awt.event.KeyAdapter()
//{
//public void keyTyped(java.awt.event.KeyEvent e) {
//String aa = field.getText();
// // TODO Auto-generated Event stub keyTyped()
//System.out.println("keyTyped"+aa);
//}
//
//});
@SuppressWarnings({"deprecation","deprecation","deprecation","deprecation","deprecation"})
publicstaticvoid main(String args[]){
javax.swing.JFrame frame =new javax.swing.JFrame("foo");
frame.setDefaultCloseOperation( javax.swing.JFrame.EXIT_ON_CLOSE );
String[] dict ={"Team","meeting","project","review","client","call","orginization","team"};
JTextField field = AutoCompleteDocument.createAutoCompleteTextField( dict );
System.out.println("keyTyped"+dict);
BoxLayout layout =new BoxLayout( frame.getContentPane(),BoxLayout.X_AXIS );
frame.getContentPane().setLayout( layout );
frame.getContentPane().add(new javax.swing.JLabel("Text Field: ") );
frame.getContentPane().add(field);
frame.show();
}
}

