0

Possible Duplicate:
How to list suggestions to when typing inside the text field

Is there any way to get predictive text in JTextField in java swing? Like if i want to get the name of the city from the user, then it should predict the city.

Community
  • 1
  • 1

3 Answers3

1

SwingX provides auto-complete feature: http://swingx.java.net/

Puce
  • 37,247
  • 13
  • 80
  • 152
0

I have an auto complete in some of my programs. Unfortunately I cannot find where I get the info on the internet. I post the code I have, but I am not the "original" writer of this AutoCompleteDocument class. If you find it on the internet give me the link so the credit can be given to the original writer.

public class AutoCompleteDocument extends PlainDocument {

    private final List<String> dictionary = new ArrayList<String>(); 
    private final JTextComponent jTextField;

    public AutoCompleteDocument(JTextComponent field, String[] aDictionary) {
        jTextField = field;
        dictionary.addAll(Arrays.asList(aDictionary));
    }

    public void addDictionaryEntry(String item) {
        dictionary.add(item);
    }

    @Override
    public void 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);
            jTextField.setCaretPosition(offs + str.length());
            jTextField.moveCaretPosition(getLength());
        }
    }

    public String autoComplete(String text) {
        for (Iterator<String> i = dictionary.iterator(); i.hasNext();) {
            String word = i.next();
            if (word.startsWith(text)) {
                return word.substring(text.length());
            }
        }
        return null;
    }  
}

then to use it simply initialise it with something like that

AutoCompleteDocument autoCompleteDoc;

autoCompleteDoc = new AutoCompleteDocument(aJTextField, anArray);
aJTextField.setDocument(autoCompleteDoc);

Hope it will help

HpTerm
  • 8,151
  • 12
  • 51
  • 67
0

Here is one possible implementation:

public class Predict
{
    private final static String [] COLORS = new String [] {"red", "orange", "yellow", "green", "cyan", "blue", "violet"};

    public static void main (String [] args)
    {
        final JTextField field = new JTextField ();

        field.getDocument ().addDocumentListener (new DocumentListener()
        {
            @Override
            public void removeUpdate (DocumentEvent e)
            {
                // Do nothing
            }

            @Override
            public void insertUpdate (DocumentEvent e)
            {
                if (e.getOffset () + e.getLength () == e.getDocument ().getLength ())
                    SwingUtilities.invokeLater (new Runnable()
                    {
                        @Override
                        public void run ()
                        {
                            predict (field);
                        }
                    });
            }

            @Override
            public void changedUpdate (DocumentEvent e)
            {
                // Do nothing
            }
        });

        JFrame frame = new JFrame ("Auto complete");
        Container contentPane = frame.getContentPane ();
        contentPane.setLayout (new BorderLayout ());
        contentPane.add (field, BorderLayout.CENTER);
        frame.pack ();
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.setVisible (true);
    }

    private static void predict (JTextField field)
    {
        String text = field.getText ();

        String prediction = null;

        for (String color: COLORS)
        {
            if (color.startsWith (text) && !color.equals (text))
            {
                if (prediction != null) return;

                prediction = color;
            }
        }

        if (prediction != null)
        {
            field.setText (prediction);

            field.setCaretPosition (text.length ());
            field.select (text.length (), prediction.length ());
        }
    }
}
Mikhail Vladimirov
  • 13,572
  • 1
  • 38
  • 40