Rowan Frank
Rowan Frank

Reputation: 117

how to fill combobox with database data java and hibernate

here is my code: In dao class for reading data from DB

    public static List<Animals> read() {
    List<Animal> a = new ArrayList<Animal>();
    Transaction tran = null;
    Session session = NewHibernateUtil.getSessionFactory().openSession();
    try {
        tran = session.beginTransaction();
        a = session.createQuery("from Animal").list();
    } catch (RuntimeException e) {
        e.printStackTrace();
    } finally {
        session.flush();
        session.close();
    }
    return a;
}

and jframe:

List<Animal> animals = AnimalDao.read();

public void addCombo(){
for(Animal a : animals){ combo.addItem(a);}

As a result my comboBox displays things like: model.Animals@5a0ffc79 Can you help me figure it out whats missing? thanks in advance!

Upvotes: 1

Views: 225

Answers (1)

Nir Levy
Nir Levy

Reputation: 12953

By default, when using objects (rather than strings) in a JcomboBox, the value that's being displayed in the combo box will be the toString() method of the object. So the simple option will be to implement toString() on your Animal class with the value you want to display.

Alternatively, if this is not enough, you can use cellRenderer. you can see this guide for usage

Upvotes: 1

Related Questions