• Post Reply Bookmark Topic Watch Topic
  • New Topic

key pressed in JList and selecting the item based on that

 
aminur rashid
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have a JList with the items in sorted order.Now I want that if a person presses any key (say K) then the first item starting with K should be selected.Hmmm I can do it by addding a key listener to the list and cheking all the items in the list ,by traversing through the whole lenght of JList and selecting the item if it starts with the character of the key pressed.
But i was thinking if there is any better way to do that?
Regards Amin
 
Chantal Ackermann
Ranch Hand
Posts: 508
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use a hashmap with the first letters as keys and the index of the first word with this first letter as values. you would have to update this hashmap everytime the list is updated. the hashmap would be much faster then iterating through the whole list (if this list is big).
or instead of just putting the index as value in the hashmap you could put there all the words as TreeSet (sorted) starting with the specific letter. you wouldn't need another container:
key - value:
A - TreeSet([words starting with A])
B - TreeSet([word starting with B])
etc.
cheers
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!