简体   繁体   English

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

[英]How can I put a index in a jcombobox in java?

I want to put in a jcombobox, the name and use the id for link the option select and the name. 我想在一个jcombobox中输入名称,并使用id链接选项select和名称。 I get the data of the db, but I don't know the way for add a items. 我得到数据库的数据,但是我不知道添加项目的方式。

I try to write a item, with 2 parameters, but in the combobox appear the class name, not the value : 我尝试编写一个带有2个参数的项目,但是在组合框中出现了类名,而不是值:

This is my code 这是我的代码

 rs = (ResultSet) stmt.executeQuery();

   while ( rs.next() ) {

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

Easiest way for you would be to override toString() method of the class which instances you are putting in the JCombo 's model. 对您来说,最简单的方法是重写要放入JCombo模型中的实例的类的toString()方法。 That way you get your 'nice name' for each item. 这样,您将获得每个项目的“好名字”。
That class, of course, should contain everything you need for each item, eg id and name. 当然,该类应包含每个项目所需的所有内容,例如id和name。 On selection change, you can than use the id of the selected item. 在选择更改时,您可以使用所选项目的ID。
If you cannot override 'toString()' or you want to separate objects you already have (eg if they are DTO) from the presentation objects, create your own class with only the things you need. 如果您不能覆盖'toString()'或想从表示对象中分离已经拥有的对象(例如,如果它们是DTO),则仅使用所需的对象创建自己的类。

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM