views:

387

answers:

1

Heyy;

I am developing a small swing based application with hibernate in java. And I want fill combobox from database coloumn.How ı can do that ? And I don't know in where(under initComponents, buttonActionPerformd) ı need to do.

For saving ı'am using jbutton and it's code is here :

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

 int idd=Integer.parseInt(jTextField1.getText());

 String name=jTextField2.getText();

 String description=jTextField3.getText();

 Session session = null;

 SessionFactory sessionFactory = new Configuration().configure()
    .buildSessionFactory();

 session = sessionFactory.openSession();

 Transaction transaction = session.getTransaction();

   try {


       ContactGroup con = new ContactGroup();

       con.setId(idd);

       con.setGroupName(name);
       con.setGroupDescription(description);



       transaction.begin(); 
       session.save(con); 
       transaction.commit(); 


      } catch (Exception e) {
       e.printStackTrace();
      }

      finally{
       session.close(); 
      }    

}

+1  A: 

I don't use Hibernate, but given a JPA entity named Customer and a JPA controller named CustomerJpaController, you can do something like this:

public class CustomerTest {

    public static void main(String[] args) {
        CustomerJpaController con = new CustomerJpaController();
        List<Customer> list = new ArrayList<Customer>();
        list = con.findCustomerEntities();
        JComboBox combo = new JComboBox(list.toArray());
        combo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JComboBox cb = (JComboBox) e.getSource();
                Customer c = (Customer) cb.getSelectedItem();
                System.out.println(c.getId() + " " + c.getName());
            }
        });
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(combo);
        f.pack();
        f.setVisible(true);
    }
}

Objects added to a JComboBox get their display name from the object's toString() method, so Customer was modified to return getName() for display purposes:

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

You can learn more about JComboBox in the article How to Use Combo Boxes.

trashgod