Sumeet Gavhale
Sumeet Gavhale

Reputation: 800

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.

Upvotes: 3

Views: 4530

Answers (3)

mKorbel
mKorbel

Reputation: 109823

  • 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.

Upvotes: 3

Ardiansyah Putra
Ardiansyah Putra

Reputation: 21

Try this

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

Upvotes: 1

Michael Dunn
Michael Dunn

Reputation: 816

it can't possibly work the way you're trying it.

the comboBox has to be editable before you click the button then you just need this line

cb_bkname.addItem(((JTextField)cb_bkname.getEditor().getEditorComponent()).getText());

Upvotes: 1

Related Questions