Adding items dynamically to JComboBox

末鹿安然 提交于 2019-12-11 13:10:49

问题


I have to read values from the database and add it to a jcombo box. Names of projects are read from the employee table and stored to a string arraylist. These values are then added to a string array named pro_string. I tried printing the values inside this string array and it works fine. But the values just don't seem to enter into the combobox(combo_project). Following is the code that i have used. It keeps throwing an exception "3". Please help.

public class meeting_form extends javax.swing.JFrame {

Connection mconn=new database().connect();


public meeting_form() {
    initComponents();

    add_projects();
}

public void add_projects()
{

    ArrayList<String> projects=new ArrayList<>();
    try{

        String pro="Select distinct project from employee";
        Statement pro_st=mconn.createStatement();
        ResultSet pro_rs=pro_st.executeQuery(pro);
        while(pro_rs.next())
        {
            String pro_name=pro_rs.getString("project");
            projects.add(pro_name);

        }
        int len=projects.size()-1;
        String[] pro_string=new String[len];
        for(int j=0;j<=len;j++)
        {
            pro_string[j]=projects.get(j);

        }
      combo_project.setModel(new javax.swing.DefaultComboBoxModel(pro_string));
    }
    catch(Exception e)
    {
        System.out.println(e.getMessage()+"......at reading project names");
    }

}

public static void main(String args[]) {

    try {

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new meeting_form().setVisible(true);
        }
    });
}
private javax.swing.JComboBox;

回答1:


This looks wrong to me

int len=projects.size()-1;
String[] pro_string=new String[len];
for(int j=0;j<=len;j++)
{
    pro_string[j]=projects.get(j);
}

I think it should be

int len=projects.size();
String[] pro_string=new String[len];
for(int j=0;j<len;j++)
{
    pro_string[j]=projects.get(j);
}


来源:https://stackoverflow.com/questions/15355436/adding-items-dynamically-to-jcombobox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!