将SelectedItem设置为jcombobox



要制作一个项目,我在一个jform中有一些jcombobox,您可以在其中选择一些选项,当您想要编辑某个内容时,对象(toString)的一些值会显示在另一个jform中的jcombobox中,并带有选定的值。但它不想在组合框中显示这些值。我想在组合框(toString)中显示名称+名字

try {
    ak = pdb.seekPerson(v.getBuyerId());
    coKoper.removeAllItems();
} catch (ApplicationException ae) {
    javax.swing.JOptionPane.showMessageDialog(this, ae.getMessage());
}
initiateCombo(); //adds the objects tot the combo
coBuyer.setSelectedItem(ak.toString());
}
    private void initiateCombo() {
        PersonDB pdb = new PersonDB();
        try {
            ArrayList<Persons> buyer = pdb.seekAllBuyers();
            for (Persons p : buyer) {
                coBuyer.addItem(p);
            }
}

您是否尝试覆盖类PersonstoString()方法
类似于:

@Override
public String toString() {
  return name + " " + firstname ;
}

此外,像这样使用setSelectedItem(我假设akPersons的一个实例):

coBuyer.setSelectedItem(ak);

不要忘记覆盖equals(Object o)方法;)

@Override
public boolean equals(Object o) {
  if( o instanceof Persons ){
    boolean check = /* here your own code*/;
    return check;
  }
  return false ;
}

看起来coBuyer组合框包含Persons对象。检索要选择的Persons对象并将其存储在ak中。

组合框将显示Persons对象的toString()方法。默认情况下,它显示Object.toString()。您需要在Persons类中@Override toString(),并让它返回name+firstname,或者您希望组合框显示的任何内容。

最新更新