• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

editable JComboBox

 
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
This is a pblm regarding a editable JComboBox.
Problem:
--------
I have a JComboBox of fixed value.eg 4 values. When ever new values are input,it gets added to the combo box. thus increasing the no of values in the combo box. What I require is that new value should be replaced instead of the old value.
At present I have a set of values {"first","second","third","fourth"} and when I enter a value of "mythird" instead of "third", I would like to have the ""mythird" value inserted instead of "third" ie it should be inserted at "third"s index position.. At present "mythird" gets added to list and the final list looks like {"mythird","first","second","third","fourth"} Whereas I would like to have the list {"first","second","mythird","fourth"}
I am enclosing the code where I tried but didn't meet with success..

with warm regards,
Arun.
(edited by Cindy to format code)

[This message has been edited by Cindy Glass (edited July 17, 2001).]
 
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The problem is insertItemAt() only inserts an item, not delete and insert. And it's getting inserted at the top of the list because you are specifying index 0.
So you need to remove the old element and insert the new one at the index the old element had.
Something like:
if (! isPresent)
{
int index = cbox.getSelectedIndex();
cbox.removeItemAt( index );
cbox.insertItemAt(
cbox.getSelectedItem(),index);
} // end of if loop
You may have to increment index after removing the item, I'm not 100% sure using the previous elements index will work exactly how you want, but you get the idea...
p.s.
I used the int variable to highlight the need for addressing the current element. A more succint solution might be:
if (! isPresent)
{
cbox.removeItemAt(
cbox.getSelectedIndex());
cbox.insertItemAt(
cbox.getSelectedItem(),
cbox.getSelectedIndex());
} // end of if loop

[This message has been edited by Guy Reynolds (edited July 17, 2001).]
 
reply
    Bookmark Topic Watch Topic
  • New Topic