如何在 java 中的 jcombobox 中放置索引?

How can I put a index in a jcombobox in java?

我想放入一个 jcombobox、名称并将 id 用于 link、选项 select 和名称。 我得到了数据库的数据,但我不知道如何添加项目。

我尝试编写一个带有 2 个参数的项目,但组合框中出现的是 class 名称,而不是值:

这是我的代码

 rs = (ResultSet) stmt.executeQuery();

   while ( rs.next() ) {

         cbHabitaciones.addItem(new Item(rs.getInt("id"), rs.getString("tipo") +" - " +rs.getString("precio")));
            }

最简单的方法是重写 class 的 toString() 方法,将哪些实例放入 JCombo 的模型中。这样你就可以得到每个项目的 'nice name'。
当然,class 应该包含每个项目所需的一切,例如编号和名称。在选择更改时,您可以使用所选项目的 ID。
如果您无法覆盖 'toString()' 或者您想将已有的对象(例如,如果它们是 DTO)与演示对象分开,请创建您自己的 class,只包含您需要的东西。

public class User {
    private int id;
    private String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return this.id;
    }

    public String getName() {
        return this.name;
    }

    public String toString() {
        return this.getName();
    }
}