Ahmed Ahmed - 1 month ago 4x
Java Question

Auto Prediction TextField

Okay, I've been searching how to do an auto prediction textfield for days now, and yes I found some solutions but they are completely hard to understand to be honest, and totally confusing since I'm new to Java/GUI. It would have been much easier if I had to click a button to do it, but I cant get how the program will perform such action whenever "a letter gets written". I've made a simple textfield and a button, whenever the button is clicked, the string in the textfield gets added in an arraylist, then prints the whole arraylist in another textfield(Just a simple example to test the auto prediction)

public class Phonebook {
public static ArrayList <String> names=new ArrayList <String>();
public static void main(String[] args) {
JFrame myForm=new JFrame("Phonebook");
myForm.setSize(555, 500);
myForm.setLocation(0, 0);

JButton button=new JButton("Add");
button.setSize(100, 50);
button.setLocation(450, 40);

JTextField t=new JTextField();
t.setSize(200, 60);
t.setLocation(10, 40);

JTextField ttt=new JTextField();
ttt.setSize(500, 300);
ttt.setLocation(10, 100);

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String str="";
for(int i=0;i<names.size();i++)


So I want the big textfield to auto complete the small textfield, so if I type "M", it shows only the names in the arraylist that start with an "M", the code for finding the names that start with an "M" would be easy, but making it "Automatic" sounds very difficult to me. If anyone could help me with my code instead of sending me a new whole confusing code, I would really appreciate that. Thank you.

Edit: Or I just want the code that somehow checks if a letter is written, so (if a letter gets written in the textfield), system.out.print("A");


You could try attaching a Document Listener to the text box:

textField.getDocument().addDocumentListener(new DocumentListener() {
    public void insertUpdate(DocumentEvent e) {
        // search the prediction data for the current contents 
        // of the text field
    public void removeUpdate(DocumentEvent e) {
        // do stuff
    public void changedUpdate(DocumentEvent e) {
        //Plain text components do not fire these events

I think you can then use either the insertUpdate or changedUpdate functions to get a hook into the point when text is changed, access the textFields values and put your auto-complete functionality in there.