你的方式没有任何成功,但我在早期的项目中找到了解决方案。您可以通过执行以下操作来设置 JComboBox 的模型:
//load the list of objects to use
ContainerClass[] allOptions = ContainerClass.getAll();
//create an EventList with this list and set is as the combobox model
final EventList<ContainerClass> eventList = GlazedLists.eventList(Arrays.asList(allOptions));
comboBox.setModel(new DefaultComboBoxModel<ContainerClass>(allOptions));
//finally initialize the combobox by SwingUtilities if done on a non-UI thread
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
AutoCompleteSupport<ContainerClass> install =
AutoCompleteSupport.install(comboBox, eventList);
install.setFilterMode(TextMatcherEditor.CONTAINS);
install.setHidesPopupOnFocusLost(true);
install.setSelectsTextOnFocusGain(false);
install.setCorrectsCase(false);
}
});
并使用 ContainerClass,例如:
class ContainerClass{
int id;
String company;
//helper method to get all the objects needed
static ContainerClass[] getAll(){
ContainerClass test = new ContainerClass();
test.id = 2;
test.company = "abc";
return new ContainerClass[]{test,test,test};
}
@Override
//this String is what actually will be displayed in the combobox
public String toString(){return "(" + id + ") " + company;}
}
我假设您的 JComboBox 具有以下类型:
JComboBox<ContainerClass> comboBox;
(我必须混淆所有变量的名称,因此代码中可能存在错误。请告诉我,我会更正它们)
所以回顾一下。GlazedLists 使用模型来获取名称,它再次向ContainerClass询问它的 toString() 方法,该方法将返回名称以显示在 JComboBox 中。
请注意,当您调用comboBox.getSelectedItem()时,它将返回ContainerClass类型的对象,如果不是有效选择,则返回 null。
更新
如果您希望能够控制顺序和名称,则需要为 ComboBox 实现自己的模型。发现这似乎很好地解释了它:
class MyComboBoxModel extends AbstractListModel implements ComboBoxModel {
String[] ComputerComps = { "Monitor", "Key Board", "Mouse", "Joy Stick",
"Modem", "CD ROM", "RAM Chip", "Diskette" };
String selection = null;
public Object getElementAt(int index) {
return ComputerComps[index];
}
public int getSize() {
return ComputerComps.length;
}
public void setSelectedItem(Object anItem) {
selection = (String) anItem; // to select and register an
} // item from the pull-down list
// Methods implemented from the interface ComboBoxModel
public Object getSelectedItem() {
return selection; // to add the selection to the combo box
}
}