如何在 JComboBox 中显示自定义对象(使用 toString)

How to display custom objects (with toString) in a JComboBox

我对 Java 比较陌生,所以请记住这一点...

我有一个 swing GUI,其中包含一个 JComboBox。 我希望用户 select 一个 ArrayList<Person> 选项。 请注意,我也可以使用数组。 我以前使用过 JComboBox,但只使用过字符串。 Person class 有一个 toString() 方法,我想用它来获取应该代表 JComboBox 中的对象的文本。

稍后按下 JButton 时,应将 selected Person 对象(同一个)添加到另一个 ArrayList 以进行进一步操作。

我想让按钮做这样的事情:

Person selectedPerson = (Person) myComboBox.getselectedItem();

但是,我需要以某种方式将那些 Person 对象放入那个东西中。 我尝试使用:

myComboBox.setModel(new DefaultComboBoxModel<>(aListOfStuff);

我什至尝试制作自己的模型:

public class DropDownModel extends DefaultComboBoxModel<Person> implementsMutableComboBoxModel<Person>

但是 setModel 方法需要 none 个。


我在 Whosebug 上看到过其他类型的类似问题,但其中 none 回答了我的问题。我还注意到有人提到渲染器 class 或类似的东西。

再次: 我希望 ArrayList 在 JComboBox 中具有其 Person 对象 selectable 以便我可以使用 Person tempPerson = (Person) myComboBox.getSelectedObject();.

访问 selected 对象

我必须自己制作模型吗class?

我停止在 JList 中显示它们。使用自定义模型:

public class ListBoxModel extends AbstractListModel<Person> implements Iterable<Person>

我需要类似的东西吗?

这可能吗?

一些例子:

myComboBox.setModel(new DefaultComboBoxModel<>(s.getPersonListAsArray()));
cbRemoveClass.setModel(new DefaultComboBoxModel<>(t.getClasses().toArray(new String[t.getClasses().size()])));
someOtherComboBox.setModel(new DropDownModel(dlModel.getList())); // trying to use my custom model

Again: I want an ArrayList to have its Person objects selectable in a JComboBox

这不是它的工作原理。 ArrayList 对组合框没有任何意义。数据需要存放在ComboBoxModel.

因此您需要将 ArrayList 中的数据添加到模型中。

您编写了一个简单的循环来遍历 ArrayList,然后使用组合框便捷方法将一个项目添加到模型中:

for (each item in the ArrayList)
    comboBox.addItem( theItem );

我知道我来晚了,但这是你要找的答案:

JComboBox<ProtocolInterface> protocolCombo = new javax.swing.JComboBox<>();
HashSet<ProtocolInterface> protocols=this.myDevice.getSupportedProtocols();
protocolCombo.setModel(new javax.swing.DefaultComboBoxModel<ProtocolInterface>(protocols.toArray(new ProtocolInterface[protocols.size()])));

只需确保您的对象(在本例中为 ProtocolInterface)有一个 "toString" 方法来显示您想要的文本,如下所示:

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