如何使用休眠填充JComboBox?

时间:2019-01-06 08:43:21

标签: java database hibernate swing jcombobox

我正在创建一个Swing应用程序。我想使用Hibernate使用数据库中的数据填充JComboBox。以下是我的代码:

Session sess=sf.openSession();
Transaction tx=sess.beginTransaction();

List<Employee> company= (List<Employee>)sess.createQuery("from Company").list();
for(Company e:company) 
{
    String[] item= {Integer.toString(e.getID()),e.getName()};
}

1 个答案:

答案 0 :(得分:0)

可以这样做:

import javax.swing.*;
import java.awt.FlowLayout;
import java.util.*;

public class JComboBoxExample {

  public static void main(String[] args) {

    List<Employee> employeesFromDatabase = Arrays.asList(
        new Employee(101, "John"),
        new Employee(102, "Kevin"),
        new Employee(103, "Sally"),
        new Employee(104, "Sara"));

    JComboBox<String> comboBox = new JComboBox<>();

    for (Employee employee : employeesFromDatabase) {

      StringJoiner stringJoiner = new StringJoiner(", ");
      stringJoiner.add(Integer.toString(employee.getId()));
      stringJoiner.add(employee.getName());

      comboBox.addItem(stringJoiner.toString());
    }

    JFrame f = new JFrame("Questions");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().setLayout(new FlowLayout());
    f.getContentPane().add(new JLabel("Employee"));
    f.getContentPane().add(comboBox);
    f.setBounds(300, 200, 400, 300);
    f.setVisible(true);
  }
}

class Employee {

  private int id;
  private String name;

  public Employee(int id, String name) {
    this.id = id;
    this.name = name;
  }

  public int getId() {
    return id;
  }

  public String getName() {
    return name;
  }
}