File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes editable JComboBox Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "editable JComboBox" Watch "editable JComboBox" New topic
Author

editable JComboBox

Arun Martin
Ranch Hand

Joined: Dec 01, 2000
Posts: 64
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).]
Guy Reynolds
Ranch Hand

Joined: Oct 27, 2000
Posts: 61
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).]
 
jQuery in Action, 2nd edition
 
subject: editable JComboBox
 
Similar Threads
editable JComboBox
editable JComboBox
different JComboBoxes as editors on multiple JTable rows
Problem with editable combo box!Pls Help me
JComboBox event order.