动态地将项目添加到JComboBox [英] Adding items dynamically to JComboBox

查看:116
本文介绍了动态地将项目添加到JComboBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从数据库中读取值并将其添加到jcombo框中. 从雇员表中读取项目的名称,并将其存储到字符串数组列表中.然后将这些值添加到名为pro_string的字符串数组中.我尝试在此字符串数组中打印值,并且效果很好.但是这些值似乎似乎没有输入到combobox(combo_project)中.以下是我使用的代码.它总是抛出异常"3".请帮忙.

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;

推荐答案

在我看来,这是错误的

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

我认为应该是

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

这篇关于动态地将项目添加到JComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆