Heyy;
我正在使用java中的hibernate开发一个基于swing的小应用程序.我想从数据库coloumn填充组合框.我怎么能这样做?
而且我不知道我需要在哪里(在initComponents下,buttonActionPerformd).
为了使用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();
}
}
解决方法:
我不使用Hibernate,但是给定一个名为Customer的JPA实体和一个名为CustomerJpaController的JPA控制器,你可以这样做.
更新:代码已更新,以反映切换到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 https://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 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);
}
}
添加到JComboBox的对象从对象的toString()方法获取其显示名称,因此修改了Customer以返回getName()以用于显示目的:
@Override
public String toString() {
return getName();
}
标签:jcombobox,java,database,hibernate,swing
来源: https://codeday.me/bug/20190917/1808860.html