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

做~自己de王妃 提交于 2019-12-12 15:19:53

问题


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.


回答1:


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




回答2:


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());



回答3:


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);
      }
    }


来源:https://stackoverflow.com/questions/14307582/how-to-insert-items-to-a-jcombobox-at-runtime-and-save-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!