将数据从数据库加载到List并将其添加到组合框

时间:2015-08-11 21:12:30

标签: java swing

我的目标是将单个数据库列中的值加载到列表中并将它们添加到JComboBox中。

我知道如何将数据从数据库加载到JComboBox但我想首先将其加载到列表中然后将此列表添加到JComboBox。

这是我迄今为止所做的代码。

学校名单........................

import Connection.Javaconnect;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public final class SchoolList {

    Connection conn = null;
    ResultSet rs = null;
    PreparedStatement pst = null;

    List <String> SchoolList;

    private static SchoolList obj = null;

    private SchoolList() {
        conn = Javaconnect.ConnecrDb();
        SchoolList = new ArrayList();
        SchoolList();
    }

    public List<String> getSchoolList() {
        return SchoolList;
    }

    public void setSchoolList(List<String> SchoolList) {
        this.SchoolList = SchoolList;
    }

    public static SchoolList getObj() {
        if (obj == null) {
            obj = new SchoolList();
        }
        return obj;
    }

    public void SchoolList() {
        try {
            String sql = "Select School from School order by ID";
            pst = conn.prepareStatement(sql);
            rs = pst.executeQuery();
            while (rs.next()) {
                String Class = rs.getString("School");
                SchoolList.add(Class);
            }

            System.out.println(SchoolList);
        } catch (SQLException e) {
            System.out.println(e);

        } finally {
            try {
                rs.close();
                pst.close();
            } catch (SQLException e) {

            }
        }
    }

}

现在我通过getSchoolList()访问列表但是我得到java.lang.NullPointerException

public class Loadlist {

    SchoolList schoollist;

    public Loadlist() {

        SchoolList.getObj();

        System.out.println(schoollist.getSchoolList());

    }

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Loadlist();
            }
        });
    }

}

0 个答案:

没有答案