Java Q&A
by Jason Wraxall

Listing One
package cybernostics.framework.dialogs;
import javax.swing.DefaultComboBoxModel;
import java.util.Arrays;
import java.util.Vector;
import java.util.Iterator;
public class SortedComboBoxModel extends DefaultComboBoxModel
{
    public SortedComboBoxModel()
    {
        super();
    }
    public SortedComboBoxModel(final Object items[])
    {
        super();
        int i,c;
        for ( i=0,c=items.length;i<c;i++ )
        {    addElement(items[i]);
        }
    }
    public SortedComboBoxModel(Vector v)
    {
        for(Iterator it = v.iterator(); it.hasNext();)
        { addElement( it.next() );
        }
    }
    // Binary search before insert - assumes sorted array
    public void addElement(Object anObject)
    {
        // Similar algorithm to Arrays.BinarySearch()
        int low = 0;
        int high = getSize()-1;
        int iPlaceToInsert = -1;
        
        while (low <= high)
        {
            Object midVal = getElementAt(mid);
            int cmp = ((Comparable)anObject).compareTo(midVal);
            if (cmp < 0)
            {   high = mid - 1;
            }
            else
            {   if (cmp > 0)
                {   low = mid + 1;
                }
                else  // equal
                {   iPlaceToInsert = mid;
                    break;
                }
            }
        }
        if(iPlaceToInsert == -1)
        {   iPlaceToInsert = low;
        }
        if(iPlaceToInsert >= getSize())
        {   super.addElement(anObject); // just add to end
        }
        else
        {   insertElementAt(anObject,iPlaceToInsert);
        }
    }
}


Listing Two
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import cybernostics.framework.dialogs.*;
public class Example1  
{
    public static void main( String[] args )
    {
        // Create new test app frame
        JFrame f = new JFrame("SortedComboBoxModel Test");
        f.setSize(400,300);
        f.addWindowListener(new WindowAdapter()
        {   public void windowClosing(WindowEvent e)
            {   System.exit(0);
            } });
        // Create a combobox (with a sorted model) and add some items //
        JComboBox jcb = new JComboBox( new SortedComboBoxModel() );
        jcb.addItem("Jerome");
        jcb.addItem("Zelda");
        jcb.addItem("Abram");
        jcb.addItem("Keith");
        jcb.addItem("Jeremy");
        jcb.addItem("Abraham");

        JPanel jp = new JPanel();     // create a frame
        f.getContentPane().add(jp);   // add the panel to it
        jp.add(jcb);                  // add the combobox to the panel
        f.pack();                     // adjust size using layouts
        f.setVisible(true);           // Now show the frame
    }
} 


Listing Three
package cybernostics.framework.dialogs;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
//_________________________________________________________
public class ComboBoxAutoCompleteMgr implements ActionListener
//_________________________________________________________
{
    //_________________________________________________________
    // 'package protected' access members
    //_________________________________________________________

     /** Combobox controlled by this class */
     JComboBox ManagedCB;
     ItemCreator creator;
    /** @param jcb   ComboBox to manage. This constructor ensures that the
    *                   combobox is editable. */
    //________________________________________________________________________
    public ComboBoxAutoCompleteMgr(JComboBox jcb)
    //________________________________________________________________________
    {
        ManagedCB = jcb;
        ManagedCB.setEditable(true);
        // Get a pointer to the combobox's editor component. We're assuming it
        // is a JTextField.
        JTextField jtf = (JTextField)ManagedCB.getEditor().getEditorComponent();
        jtf.addActionListener(this);
        // Register a listener to repond to changes in the combobox's editor
        // We're only interested in additions
       jtf.getDocument().addDocumentListener( new DocumentListener()
        {
            public void changedUpdate(DocumentEvent ev){}   // Nil respose
            public void removeUpdate(DocumentEvent ev){}    // Nil respose
            public void insertUpdate(DocumentEvent ev)
            {
                // Kick off the following thread after this response thread has finished
                // Otherwise we get an exception trying to update the list model
                // within a response function.
                SwingUtilities.invokeLater(new Runnable()
                {
                    public void run()
                    {    FindAutoCompleteText(((JTextComponent)ManagedCB.getEditor().getEditorComponent()).getText());
                    }
                });
            }

        });
    }
    //________________________________________________________________________
    public void setItemCreator( ItemCreator ic )
    //________________________________________________________________________
    {
        creator = ic;
    }
    //________________________________________________________________________
    public void actionPerformed(ActionEvent ae)
    //________________________________________________________________________
    {   JTextField jtf = (JTextField)ManagedCB.getEditor().getEditorComponent();
        String s = jtf.getText();
        jtf.getCaret().setDot(jtf.getText().length());
        for( int i = 0; i < ManagedCB.getItemCount(); i++ )
        {   Object o = ManagedCB.getItemAt( i );
            String sTemp = o.toString();
            if(sTemp.equals(s))
            {   return;
            }
        }
        System.out.println(ae);     
        if( creator != null )
        {   creator.createItemFor( s, (DefaultComboBoxModel)ManagedCB.getModel() );
        }
    }
   //________________________________________________________________________
    public void FindAutoCompleteText(String s)
    //________________________________________________________________________
    {   for( int i = 0; i < ManagedCB.getItemCount(); i++ )
        {   Object o = ManagedCB.getItemAt( i );
            String sTemp = o.toString();
            // Don't do anything if the text exactly matches...
            if(sTemp.equals(s))
            {   return;
            }
            if( sTemp.startsWith(s) )
            {
                ManagedCB.setSelectedIndex(i);
                JTextComponent jtc = (JTextComponent)ManagedCB.getEditor().getEditorComponent();
                // Insert the suggested text
                jtc.setText(sTemp);
                // Select the inserted text from the end to the current
                // edit position.
                Caret c = jtc.getCaret();
                c.setDot(sTemp.length());
                c.moveDot(s.length());
                break;
            }
        }
    }
    public static ComboBoxAutoCompleteMgr createAutoSelectComboBox()
    {
        JComboBox jcb = new JComboBox(new SortedComboBoxModel());
        ComboBoxAutoCompleteMgr acm = new ComboBoxAutoCompleteMgr(jcb);
        return acm;
    }
}





1

