1

嘿嘿;

我正在用java中的hibernate开发一个基于swing的小型应用程序。我想从数据库列中填充组合框。我怎么能这样做?

而且我不知道我需要在哪里(下initComponentsbuttonActionPerformd)做。

为了节省,我正在使用 jbutton,它的代码在这里:

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

1 回答 1

5

我不使用 Hibernate,但是给定一个名为的 JPA 实体Customer和一个名为 的 JPA 控制器CustomerJpaController,您可以执行类似的操作。

更新:更新代码以反映切换到 EclipseLink (JPA 2.1) 作为持久性库。

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JComboBox;
import javax.swing.JFrame;

/**
* @see http://stackoverflow.com/a/2531942/230513
*/
public class CustomerTest implements Runnable {

    public static void main(String[] args) {
        EventQueue.invokeLater(new CustomerTest());
    }

    @Override
    public void run() {
        CustomerJpaController con = new CustomerJpaController(
            Persistence.createEntityManagerFactory("CustomerPU"));
        List<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);
    }
}

添加到 aJComboBox的对象从对象的方法中获取其显示名称toString(),因此Customer被修改为返回getName()以用于显示目的:

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

JComboBox您可以在文章如何使用组合框中了解更多信息。

于 2010-03-28T04:56:20.613 回答