Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / GUI / June 2004

Tip: Looking for answers? Try searching our database.

JList, JComboBox - first letter matching - how to set it up?

Thread view: 
T E Schmitz - 03 Jun 2004 14:00 GMT
Hello,

(1)
I have a sorted JList and I would like to select the item that matches  the
user's keystrokes:

example list {"Cardiff", "Carlisle", "Edinburgh", "Glasgow",  "Liverpool",
"London"}

'L' should select "Liverpool", 'Lo' "London".

I've seen a couple of postings from which I gather that this behaviour is
already implemented. But I am not sure whether I need to implement a
KeyListner and buffer the keystrokes and then call getNextMatch() with the
cached string?

I'd appreciate it if anyone could point me in the right direction.

(2)
I need a similar feature for JComboBox. Again, does anyone have any ideas
how to implement this?

Regards,
Tarlika Elisabeth Schmitz
Michael Rauscher - 04 Jun 2004 22:04 GMT
Hi Tarlika,

T E Schmitz schrieb:
> Hello,
>
[quoted text clipped - 17 lines]
> I need a similar feature for JComboBox. Again, does anyone have any ideas
> how to implement this?

Have a look at
http://javaalmanac.com/egs/javax.swing/combobox_CbMultiKey.html

Hope it helps
Michael
T E Schmitz - 06 Jun 2004 20:24 GMT
> Hi Tarlika,
>
[quoted text clipped - 22 lines]
> Hope it helps
> Michael

Hello Michael,

That'll at least sort first letter matching for the JComboBox.
Brilliant, thanks! That's the second time you've helped me out, Michael,
I'll soon owe you a virtual beer (Kölsch natürlich)!

(http://www.linuxjournal.com/article.php?sid=0063 in case you don't know
the Linux beer joke).

Tarlika

Signature

Regards,

Tarlika Elisabeth Schmitz

Elisabeth Schmitz - 09 Jun 2004 19:47 GMT
> T E Schmitz schrieb:
> > (2)
[quoted text clipped - 3 lines]
> Have a look at
> http://javaalmanac.com/egs/javax.swing/combobox_CbMultiKey.html

Just in case anybody else is looking to implement first letter
matching for comboxboxes:

The suggested solution works fine but is only suitable for
non-editable comboboxes using the DefaultListCellRenderer.

I am using a non-editable combobox with a custom cell renderer, which
extends DefaultListCellRenderer. I had to slightly modify the above
solution:

1) I created an abstract class KeyMatchListCellRenderer subclassing
DefaultListCellRenderer adding a getText(Object o) method which is to
return the string that getListCellRendererComponent(...) would produce
for this object.

2) I subclassed JComboBox with an inner class implementing
JComboBox.KeySelectionManager.

3) the KeySelectionManager code:

/**
* This <code>KeySelectionManager</code> will handle selections based
* on multiple key strokes. One or more key strokes will form a match
* string. The comboxbox is searched for an element the first
* characters of which match the match string. Comparison is
* case-insensitive.
*/
private class MyKeySelectionManager
   implements JComboBox.KeySelectionManager
{
   /** Accumulated key strokes. */
   String pattern = "";

   /** Time previous key was hit. */
   long lastKeyTime = 0;

   /**
    * Returns the row that should become selected based on the key
    * the user pressed and the model. If a key is typed less than
    * 300 ms after the last key stroke, it will be appended to the
    * previous character[s] to form a match string. The combobox
    * elements are compared against the match string in order to
    * find an element starting with these characters.
    *
    * <P>
    * Modifier keys are ignored; therefore the comparison is
    * case-insensitive. The elements are searched beginning after
    * the currently selected element and then from the first element
    * down to the currently selected one.
    * </p>
    *
    * @param keyChar key pressed.
    * @param model data model used by the combobox.
    *
    * @return row index of element to be selected.
    */
   public int selectionForKey (
       char          keyChar,
       ComboBoxModel model)
   {
       int size = model.getSize();
       if (size < 1)
       {
           return (-1);
       }

       /* Find index of selected item. */
       int    selectedIndex = 01;
       String keyString = ("" + keyChar).toLowerCase();

       Object selectedItem = model.getSelectedItem();
       if (selectedItem != null)
       {
           for (int i = 0; i < model.getSize(); i++)
           {
               if (selectedItem.equals(model.getElementAt(i)))
               {
                   selectedIndex = i;
                   break;
               }
           }
       }

       /* If last keyChar was typed less than 300 ms ago, append to
current pattern. */
       long currentTime = System.currentTimeMillis(); /* Get current
time. */
       pattern     = ((currentTime - lastKeyTime) < 300)
           ? (pattern + keyString) : keyString;
       lastKeyTime = currentTime; /* Save current time. */

       int start = (selectedIndex < 0) ? 0 : selectedIndex;
       int i = ((start + 1) >= size) ? 0 : (start + 1);
       while (i != start)
       {
           String text    = "";
           Object element = model.getElementAt(i);

           if (element != null)
           {
               if (cellRenderer instanceof KeyMatchListCellRenderer)
               {
                   text =
((KeyMatchListCellRenderer)cellRenderer).getText(element);
               }
               else
               {
                   text = element.toString();
               }
               if (text != null)
               {
                   text = text.toLowerCase();
                   if (text.startsWith(pattern))
                   {
                       return (i);
                   }
               }
           }
           i = ((i + 1) >= size) ? 0 : (i + 1);
       }

       return (-1);
   }
}
Elisabeth Schmitz - 10 Jun 2004 10:23 GMT
> 3) the KeySelectionManager code:

One correction: start the loop on the selected element and advance the
counter at the bottom of the loop. Otherwise you will jump to the next
but one match if the first part of the match string matches another
element:

int start = (selectedIndex < 0) ? 0 : selectedIndex;
int i = start;
do

<snip>...</snip>

i = ((i + 1) >= size) ? 0 : (i + 1);
} while (i != start);

Regards,
Tarlika Elisabeth Schmitz


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.