基于JCombobox Java

时间:2018-05-03 09:19:40

标签: java jframe jcombobox

我刚刚开始用Java开发,所以我有一个新手问题,我有一个Jcombobx,它使用这个函数从我的数据库中填充:

private void fill(){
   try{
       con = DriverManager.getConnection("jdbc:....");
       Statement pst = con.createStatement();
       String sql = "select * from student";
       ResultSet rs = pst.executeQuery(sql);
       while(rs.next()){
            jCombo.addItem(rs.getString("strudent_name");
       }
   } catch (Exception e){
      System.out.println(e.getMessage);
 }

代码正常工作,组合从我的数据库中填充,下一步是根据组合框中的selectedItem从我的数据库中填充另一个JFrame,当我在PHP中开发时我知道这很容易,因为我只有将id放入选择值和显示的名称中。 在android中我可以通过Intent发送,但我不知道如何在jaa中做,因为必须打开的下一个JFrame必须使用来自其他表的信息来获取有关所选学生的详细信息。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

首先为学生

创建一个包装类
public class Student
{

    private int id;
    private String name;
    //more fields here like grades, subjects etc

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



    public int getId()
    {
        return this.id;
    }



    public void setId(int id)
    {
        this.id = id;
    }



    public String getName()
    {
        return this.name;
    }



    public void setName(String name)
    {
        this.name = name;
    }



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


}

然后你像这样声明JComboBox

JComboBox<Student> jCombo = new JComboBox<>();

然后

private void fill(){
   try{
       con = DriverManager.getConnection("jdbc:....");
       Statement pst = con.createStatement();
       String sql = "select * from student";
       ResultSet rs = pst.executeQuery(sql);
       while(rs.next()){
        Student student = new Student(rs.getInt("student_id") , rs.getString("student_name"));     
         jCombo.addItem(student);
       } // while end

   } catch (Exception e){
      System.out.println(e.getMessage);
 }

点击某个按钮后,您可以通过

获取所选学生的ID
showDetailsButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0)
        {
            Student selectedStudent = (Student) jCombo.getSelectedItem();
            new StudentDetails(selectedStudent.getId());

        }
    });

其中StudentDetails是另一个JFrame

class StudentDetails extends JFrame 
{
    public StudentDetails(int studentID)
    {
        // "Select * from student where student_id =" + studentID;
        super();
        add(new JLabel("Detail of student with id " + studentID + " goes here"));
        setVisible(true);
        setSize(100, 100);

    }
}