问题
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