How to resolve an auto-completion problem

This is only a 4 lines of code can you resolve it.  I am getting error with this in this.combobox and add in line 26
snippet #. . . 61 shows an example of a simple glazed list from
http://today.java.net/pub/a/today/2007/07/19/adding-auto-completion-to-swing-comboboxes.html
snippet #. . . 62 is my modification but cant get it to work.  The code we use earlier is too cumbersome.  
package autocompletion;

import java.awt.BorderLayout;
import java.awt.Component;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.swing.AutoCompleteSupport;

public class SimpleGlazedListVE {

	public static void main(String[] args) {
		Object[] elements = new Object[] { "Ester", "Jordi", "Jordina",
		        "Jorge", "Sergi" };
		this.comboBox = new JComboBox();
		AutoCompleteSupport support = AutoCompleteSupport.install(
		        this.comboBox, GlazedLists.eventListOf(elements));
		System.out.println("Is editable - " + this.comboBox.isEditable()
		        + ". Surprise!");
		
		JFrame f = new JFrame();
		JPanel p = new JPanel();
		f.add(support, BorderLayout.CENTER);
		f.pack();
		f.setVisible(true);
		
	}
}

Open in new window

Object[] elements = new Object[] { "Ester", "Jordi", "Jordina", "Jorge", "Sergi" };
this.comboBox = new JComboBox();

AutoCompleteSupport support = AutoCompleteSupport.install(
        this.comboBox, GlazedLists.eventListOf(elements));

System.out.println("Is editable - " + this.comboBox.isEditable() + ". Surprise!");

Open in new window

Vanavah EdwardsAsked:
Who is Participating?
 
for_yanCommented:

this by the way AutoCompleteComboBox without any Glazed lists
from http://www.java.happycodings.com/Java_Swing/code6.html
and it works for me:

import javax.swing.*;



import java.awt.Component;
import java.util.*;
import javax.swing.*;
import javax.swing.plaf.basic.BasicComboBoxEditor;
import javax.swing.text.*;

public class AutoCompleteComboBox extends JComboBox
{
	private static final Locale[] INSTALLED_LOCALES = Locale.getAvailableLocales();
	private ComboBoxModel model = null;
	public static void main(String[] args)
	{
		JFrame f = new JFrame("AutoCompleteComboBox");
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		AutoCompleteComboBox box = new AutoCompleteComboBox(INSTALLED_LOCALES, false);
		f.getContentPane().add(box);
		f.pack();
		f.setLocationRelativeTo(null);
		f.setVisible(true);
	}
	/**	 * Constructor for AutoCompleteComboBox -
	* The Default Model is a TreeSet which is alphabetically sorted and doesnt allow
	duplicates.	 * @param items	 */
	public AutoCompleteComboBox(Object[] items, boolean caseSensitive)
	{
		super(items);
		model = new ComboBoxModel(items);
		setModel(model);
		setEditable(true);
		setEditor(new AutoCompleteEditor(this, caseSensitive));
	}
	/**	 * Constructor for AutoCompleteComboBox -
	* The Default Model is a TreeSet which is alphabetically sorted and doesnt allow
	duplicates.	 * @param items	 */
	public AutoCompleteComboBox(Vector items, boolean caseSensitive)
	{
		super(items);
		model = new ComboBoxModel(items);
		setModel(model);
		setEditable(true);
		setEditor(new AutoCompleteEditor(this, caseSensitive));
	}
	/**	 * Constructor for AutoCompleteComboBox -
	* This constructor uses JComboBox's Default Model which is a Vector.
	* @param caseSensitive	 */
	public AutoCompleteComboBox(boolean caseSensitive)
	{
		super();
		setEditable(true);
		setEditor(new AutoCompleteEditor(this, caseSensitive));
	}

	/*	 * ComboBoxModel.java	 */
	public class ComboBoxModel extends DefaultComboBoxModel
	{
		/**		 * The TreeSet which holds the combobox's data (ordered no duplicates)
		*/
		private TreeSet values = null;
		public ComboBoxModel(List items)
		{
			super();
			this.values = new TreeSet();
			int i, c;
			for (i = 0, c = items.size(); i < c; i++)
				values.add(items.get(i).toString());
			Iterator it = values.iterator();
			while (it.hasNext())
				super.addElement(it.next().toString());
		}
		public ComboBoxModel(final Object items[])
		{
			this(Arrays.asList(items));
		}
	}

	/*	 * AutoCompleteEditor.java	 */
	public class AutoCompleteEditor extends BasicComboBoxEditor
	{
		private JTextField editor = null;
		public AutoCompleteEditor(JComboBox combo, boolean caseSensitive)
		{
			super();
			editor = new AutoCompleteEditorComponent(combo, caseSensitive);
		}
		/**
		* overrides BasicComboBox's getEditorComponent to return custom TextField
		(AutoCompleteEditorComponent)		 */
		public Component getEditorComponent()
		{
			return editor;
		}
	}

	/*	 * AutoCompleteEditorComponent.java	 */
	public class AutoCompleteEditorComponent extends JTextField
	{
		JComboBox combo = null;
		boolean caseSensitive = false;
		public AutoCompleteEditorComponent(JComboBox combo, boolean caseSensitive)
		{
			super();
			this.combo = combo;
			this.caseSensitive = caseSensitive;
		}
		/**
		* overwritten to return custom PlainDocument which does the work*/
		protected Document createDefaultModel()
		{
			return new PlainDocument()
			{
				public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
				{
					if (str == null || str.length() == 0)
						return;
					int size = combo.getItemCount();
					String text = getText(0, getLength());
					for (int i = 0; i < size; i++)
					{
						String item = combo.getItemAt(i).toString();
						if (getLength() + str.length() > item.length())
							continue;
						if (!caseSensitive)
						{
							if ((text + str).equalsIgnoreCase(item))
							{
								combo.setSelectedIndex(i);
								//if (!combo.isPopupVisible())
								//	combo.setPopupVisible(true);
								super.remove(0, getLength());
								super.insertString(0, item, a);
								return;
							}
							else if (item.substring(0, getLength() + str.length()).equalsIgnoreCase(text + str))
							{
								combo.setSelectedIndex(i);
								if (!combo.isPopupVisible())
										combo.setPopupVisible(true);
									super.remove(0, getLength());
									super.insertString(0, item, a);
									return;
							}
						}
						else if (caseSensitive)
						{
							if ((text + str).equals(item))
							{
								combo.setSelectedIndex(i);
								if (!combo.isPopupVisible())
									combo.setPopupVisible(true);
								super.remove(0, getLength());
								super.insertString(0, item, a);
								return;
							}
							else if (item.substring(0, getLength() + str.length()).equals(text + str))
							{
								combo.setSelectedIndex(i);
								if (!combo.isPopupVisible())
									combo.setPopupVisible(true);
								super.remove(0, getLength());
								super.insertString(0, item, a);
								return;
							}
						}
					}
				}
			};
		}
	}
}

Open in new window

0
 
for_yanCommented:
what means snippet #61 and #62; where do i find these 61 and 62
0
 
Vanavah EdwardsAuthor Commented:
the endnig numbers of the 2 attached snippets
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
mccarlIT Business Systems Analyst / Software DeveloperCommented:
Neither of these two snippets would work, as all the code is in the main function which is STATIC and so "this" can't be used. Also, your explanation in question makes very little sense. What is the error that you are getting? And I don't see that there is anything different at all in the second snippet???
0
 
for_yanCommented:
what is the "ending numbers" ?


does class
AutoCompleteSupport  
extends JComponent or something like that.

In order to do this:
f.add(support, BorderLayout.CENTER);

AutoCompleteSupport shoudl be some component - is it extending JComboBOx ?
0
 
for_yanCommented:
I mentioned to you severla times that you should move away the stuff from main()
0
 
for_yanCommented:

method AutoCompletSupport.install
returns object of type  AutoCompletSupport:

http://publicobject.com/glazedlists/glazedlists-1.7.0/api/ca/odell/glazedlists/swing/AutoCompleteSupport.html

AutoCompletSupport does not extend component or anything of this kind (see API above).

Thereofre it makes no sense to add insatnce of AutoCompleteSupport (named support) to JFrame f:

f.add(support, BorderLayout.CENTER);

Think again and modify this.

Also move all craetion of visual elements to the constructor
of your class, and make this class extend JFrame

Look at the template I posted for you in one of the previous frames.






0
 
Vanavah EdwardsAuthor Commented:
I understand what you are saying. However, I have been trying to write a very basic auto-completion combo box to put on a panel and hoop the panel on a frame so that I can understand how it works and then trnasfer it to my program but without successs.  I copied back the same code from the site you recommended that look promising  and that didn't work.  I put them out of the main and yet that didn't work.  
0
 
for_yanCommented:
On the site wherei pointed you there was only a small snippet - it required some handling ousideof taht snippet to have it working.

OK, the program I posted above - is not a snippet - it is a fiull program and it ahs a class which extends ComboBox
- just try it forst as it is - make sure it works.

Then cereate your own frame and put this one as lement of your frame
0
 
Vanavah EdwardsAuthor Commented:
ok it works.  I now have to make my own combobox and see how to incorporate it,
0
 
for_yanCommented:

Here I added a new clss called MyClassUsingComboBox
whiich packs this combobox with autocompletion together with
lable and textfield on oone frame

Compile it, point to the main() method of MyClassUsingComboBox
and you'll see how it works.

Pay attention at how main() method
has just one line

import javax.swing.*;


import java.awt.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.plaf.basic.BasicComboBoxEditor;
import javax.swing.text.*;

public class AutoCompleteComboBox extends JComboBox
{
	private static final Locale[] INSTALLED_LOCALES = Locale.getAvailableLocales();
	private ComboBoxModel model = null;
    /*
	public static void main(String[] args)
	{
		JFrame f = new JFrame("AutoCompleteComboBox");
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		AutoCompleteComboBox box = new AutoCompleteComboBox(INSTALLED_LOCALES, false);
		f.getContentPane().add(box);
		f.pack();
		f.setLocationRelativeTo(null);
		f.setVisible(true);
	}

    */
	/**	 * Constructor for AutoCompleteComboBox -
	* The Default Model is a TreeSet which is alphabetically sorted and doesnt allow
	duplicates.	 * @param items	 */
	public AutoCompleteComboBox(Object[] items, boolean caseSensitive)
	{
		super(items);
		model = new ComboBoxModel(items);
		setModel(model);
		setEditable(true);
		setEditor(new AutoCompleteEditor(this, caseSensitive));
	}
	/**	 * Constructor for AutoCompleteComboBox -
	* The Default Model is a TreeSet which is alphabetically sorted and doesnt allow
	duplicates.	 * @param items	 */
	public AutoCompleteComboBox(Vector items, boolean caseSensitive)
	{
		super(items);
		model = new ComboBoxModel(items);
		setModel(model);
		setEditable(true);
		setEditor(new AutoCompleteEditor(this, caseSensitive));
	}
	/**	 * Constructor for AutoCompleteComboBox -
	* This constructor uses JComboBox's Default Model which is a Vector.
	* @param caseSensitive	 */
	public AutoCompleteComboBox(boolean caseSensitive)
	{
		super();
		setEditable(true);
		setEditor(new AutoCompleteEditor(this, caseSensitive));
	}

	/*	 * ComboBoxModel.java	 */
	public class ComboBoxModel extends DefaultComboBoxModel
	{
		/**		 * The TreeSet which holds the combobox's data (ordered no duplicates)
		*/
		private TreeSet values = null;
		public ComboBoxModel(List items)
		{
			super();
			this.values = new TreeSet();
			int i, c;
			for (i = 0, c = items.size(); i < c; i++)
				values.add(items.get(i).toString());
			Iterator it = values.iterator();
			while (it.hasNext())
				super.addElement(it.next().toString());
		}
		public ComboBoxModel(final Object items[])
		{
			this(Arrays.asList(items));
		}
	}

	/*	 * AutoCompleteEditor.java	 */
	public class AutoCompleteEditor extends BasicComboBoxEditor
	{
		private JTextField editor = null;
		public AutoCompleteEditor(JComboBox combo, boolean caseSensitive)
		{
			super();
			editor = new AutoCompleteEditorComponent(combo, caseSensitive);
		}
		/**
		* overrides BasicComboBox's getEditorComponent to return custom TextField
		(AutoCompleteEditorComponent)		 */
		public Component getEditorComponent()
		{
			return editor;
		}
	}

	/*	 * AutoCompleteEditorComponent.java	 */
	public class AutoCompleteEditorComponent extends JTextField
	{
		JComboBox combo = null;
		boolean caseSensitive = false;
		public AutoCompleteEditorComponent(JComboBox combo, boolean caseSensitive)
		{
			super();
			this.combo = combo;
			this.caseSensitive = caseSensitive;
		}
		/**
		* overwritten to return custom PlainDocument which does the work*/
		protected Document createDefaultModel()
		{
			return new PlainDocument()
			{
				public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
				{
					if (str == null || str.length() == 0)
						return;
					int size = combo.getItemCount();
					String text = getText(0, getLength());
					for (int i = 0; i < size; i++)
					{
						String item = combo.getItemAt(i).toString();
						if (getLength() + str.length() > item.length())
							continue;
						if (!caseSensitive)
						{
							if ((text + str).equalsIgnoreCase(item))
							{
								combo.setSelectedIndex(i);
								//if (!combo.isPopupVisible())
								//	combo.setPopupVisible(true);
								super.remove(0, getLength());
								super.insertString(0, item, a);
								return;
							}
							else if (item.substring(0, getLength() + str.length()).equalsIgnoreCase(text + str))
							{
								combo.setSelectedIndex(i);
								if (!combo.isPopupVisible())
										combo.setPopupVisible(true);
									super.remove(0, getLength());
									super.insertString(0, item, a);
									return;
							}
						}
						else if (caseSensitive)
						{
							if ((text + str).equals(item))
							{
								combo.setSelectedIndex(i);
								if (!combo.isPopupVisible())
									combo.setPopupVisible(true);
								super.remove(0, getLength());
								super.insertString(0, item, a);
								return;
							}
							else if (item.substring(0, getLength() + str.length()).equals(text + str))
							{
								combo.setSelectedIndex(i);
								if (!combo.isPopupVisible())
									combo.setPopupVisible(true);
								super.remove(0, getLength());
								super.insertString(0, item, a);
								return;
							}
						}
					}
				}
			};
		}
	}
}


class MyClassUsingComboBox extends JFrame {

    static String [] myStrings = new String[] {"a","ab","abc","cde","def"};


    public  MyClassUsingComboBox() {
        super("Using Combobox");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTextField   tf = new JTextField(10);
        JLabel lbl = new JLabel("ttrdt");
        JPanel pnl = new JPanel();
        pnl.setLayout(new FlowLayout());
        AutoCompleteComboBox box = new AutoCompleteComboBox(myStrings, false);
        pnl.add(lbl);
        pnl.add(tf);
        pnl.add(box);
        this.getContentPane().add(pnl);
            this.pack();
            this.setLocationRelativeTo(null);
            this.setVisible(true);





    }

    public static void main(String[] args) {
        new  MyClassUsingComboBox();
 }


}

Open in new window

0
 
for_yanCommented:
the above code works  but has its own quirks and does not interact correctly with the mouse selection, which should
override autocompletion, but it does not

that requires additional work - some stuf about this is written here
http://www.orbital-computer.de/JComboBox/ 
hope reading  it should help to fix this issue.
0
 
Vanavah EdwardsAuthor Commented:
I studied your sample code and it taught me how write code to call other method in a different.  So I wrote a simple program using the original auto-complete you sent me and importing swing jar class. and it worked.  The glazed list posted does not work but the SwingX autocomple does.  See the code below.  Also the samples posted are their sights are too complex and difficult to call.  It only takes one line of code to add auto-support to any combobox.  Here is the line:-
AutoCompleteDecorator.decorate(cb2); where cb2 is the combobox please see the code below.  I will award you the points because its your code that open my eyes and taught me some lessons.  Remember, although I studies java I am still ne to writing complex programs.

import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.swing.AutoCompleteSupport;

public class SimpleGlazedListVE  {

	public static void main(String[] args) {
		JFrame f = new JFrame();
		JPanel p = new JPanel();
		Object[] elements = {"","Ester","Jordi","Jordina","Jorge","Sergi"};
		JComboBox cb2 = new JComboBox(elements);
		AutoCompleteDecorator.decorate(cb2);
		p.add(cb2);
		f.add(p);
		f.setSize(200, 200);
		f.setVisible(true);
		}
}

Open in new window

0
 
for_yanCommented:
Very good, that you found the best way.
Taht's how it usually goes - and requires some experimentation -
espcially with such component like AutoComplete which is really a thing not altogether trivial
0
 
leobrahmaCommented:
May I suggest

1. Create your JFrame with your favourite IDE.
2. Add you Combo Box, give it a proper name.
3. In the constructor add your array of objects and the intruction
                AutoCompleteSupport.install(  name_of_comboBox, GlazedLists.eventListOf(elements));

     like that without instancing.

Voila, 10 minutes including downloading the GlazedLists jar, that turn it to be very cool.
0
 
Vanavah EdwardsAuthor Commented:
I was on line all day with CEFH and he has not acknowledge any of my last submission.  Mr. for_Van has been by my side and this is what caused me to solve the problem.  I tried with CEFH.  I tried with all types of codes on auto-completion on the internet.  All was complex and the glazed made me waste hours of time becuse it doesn't work only the swingx.  I would sincerely recommend him to all solution seekers more than any other expert I have dealt with.
0
 
for_yanCommented:
Yes,  SwingX seems to be simple and works pretty nicely. Thanks. Good you tried it.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.