I am trying to make a functionality for quick search of clients from database on some keystrokes from user, using an editable combobox. What i wanted to have is, user will put in some letters and if those lettters match with some clients, those clients will be remained in the current data model of the combobox.
The code is as follows.
Please fix the exception occuring in the code. Thanks in Advance !!
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Attempt to mutate in notification
import java.util.ArrayList;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
class ComboSearch extends JFrame implements CaretListener
{
private JComboBox mycombo;
private ArrayList<String> list;
private DefaultComboBoxModel<String> isolatemodel,model;
public ComboSearch()
{
setSize(400, 400);
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
mycombo=new JComboBox();
mycombo.setEditable(true);
mycombo.setBounds(30,30, 350, 50);
isolatemodel=new DefaultComboBoxModel();
model=new DefaultComboBoxModel();
list=new ArrayList();
add(mycombo);
mycombo.setModel(isolatemodel);
((JTextField)mycombo.getEditor()
.getEditorComponent()).addCaretListener(this);
setVisible(true);}
private void addElements()
{
list.add("Rambhau, Vijay Nagar");
list.add("Surya, Ashok Puri");
list.add("Mourya, Shahjapur");
list.add("Kishorji & sons, Bhopal");
list.add("Fablica & jewels, Itanagar");
list.add("Guru Kripa,Ujjain");
list.add("Hariram Nai & Bakes, Indore");
list.add("Ganesh Sev Bhandar, Harda");
list.add("Greatsome Higs, Jabalpur");
list.add("Treks and hains, Nalanda");
list.add("Tata Indora, Hoshangabad");
list.add("Paankhai Seth, Madurai");
list.add("Katappa, Shikara");
list.add("Gunjan Samosa, Vijay Nagar");
list.add("Ramesh hustlers , Vijay Nagar");
}
public void makeModels()
{
addElements();
list.stream().forEach((client) -> {
isolatemodel.addElement(client);
});
}
@Override
public void caretUpdate(CaretEvent e)
{
String searchText=((JTextField)mycombo.getEditor()
.getEditorComponent()).getText();
if(!searchText.isEmpty())
{
for(int i=0; i<isolatemodel.getSize();i++)
{
if(isolatemodel.getElementAt(i).contains(searchText))
{
model.removeAllElements();
model.addElement(isolatemodel.getElementAt(i));
}
}
mycombo.setModel(model);
mycombo.showPopup();
}
else
{
mycombo.setModel(isolatemodel);
}
}
}
public class Execute
{
public static void main(String[] args)
{
ComboSearch searchIt=new ComboSearch();
searchIt.makeModels();
}
}