简体   繁体   中英

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. 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 :

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. 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. On selection change, you can than use the id of the selected item.
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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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