简体   繁体   中英

Adding items dynamically to JComboBox

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;

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM