• Post Reply Bookmark Topic Watch Topic
  • New Topic

editable JComboBox

 
Arun Martin
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • 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..
Code:
------
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class editableComboBox extends JFrame
{
Container container;
String [] b = {"a","b","c","d","e","f"};
JComboBox cbox;
String defaultEdit ="a";
editableComboBox()
{
container=this.getContentPane();
container.setLayout(null);
cbox = new JComboBox(b);
cbox.setEditable(true);
cbox.setBounds(12,7,150,25);
cbox.configureEditorcbox.getEditor ),defaultEdit);
ComboBoxEditor cboxEditor = cbox.getEditor();
Component editorComp =
cboxEditor.getEditorComponent();
cbox.addActionListener(new CombBoxListener());
container.add(cbox);
setSize(805,550);
setVisible(true);
} // end of constructor editableComboBox
class CombBoxListener implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
boolean isPresent=false;
for (int i=0;i<cbox.getItemCount();i++)>
{
if (cbox.getItemAt(i).equals
(cbox.getSelectedItem()))
{
isPresent=true;
break;
}
} // end of for loop
if (! isPresent)
{
cbox.insertItemAt(cbox.getSelectedItem
(),0);
} // end of if loop
} // end of actionPerformed
} // end of class comboListener

public static void main(String[] a)
{
editableComboBox ob = new editableComboBox();
} // end of main
} // end of pgm
with warm regards,
Arun.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!