问题
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 theDefaultComboBoxModel
underlaying theJComboBox
, the same action (by default) is possible from outside.You have to use MutableComboBoxMode to
add
/remove Item
(s) to / fromJComboBox
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