Search code examples
javaswingactionlistenerjcomboboxcomboboxmodel

How to insert items to a jcombobox at runtime and save it


I need to save the values in my jcombobox at the runtime. What I am trying to do is after clicking on a button, I am setting it to editable = true. Then type the value in the combobox, but it doesn't save.

private void btadbknameActionPerformed(java.awt.event.ActionEvent evt) {
  if(evt.getSource()== btadbkname){
    cb_bkname.setEditable(true);
    cb_bkname.getText();
    cb_bkname.addItem(evt);
  }else{
    cb_bkname.setEditable(false);
  }
}

I have already added some elements in it on the designing level, but it's limited if some random value comes then its a problem.


Solution

    • Because it is possible to add / remove Item(s) to / from the DefaultComboBoxModel underlaying the JComboBox, the same action (by default) is possible from outside.

    • You have to use MutableComboBoxMode to add / remove Item(s) to / from JComboBox that fires event from itself (view_to_model).

    • There are excellent examples of MutableComboBoxModel by @Robin here and here.

    • For better help sooner post an SSCCE, for future readers, otherwise search for extends AbstractListModel implements MutableComboBoxModel.