为什么toString方法不能在JComboBox中获取所选项?

时间:2016-11-16 11:47:39

标签: java

我使用ArrayList将我的值从数据库绑定到JComboBox并使用StringBuilder转换每个数组,因为StringBuilder接受任何数据类型,所以我认为这是最有效的方法。

while(rs.next())
{
        departmentId = rs.getInt(1);
        departmentTypeList = rs.getString(2);

        ArrayList<DepartmentList> listDepartment = new ArrayList<DepartmentList>();

        listDepartment.add(new DepartmentList(departmentId,departmentTypeList));
        StringBuilder builder = new StringBuilder();

        for(DepartmentList s : listDepartment)
        {
           builder.append(s);
        }
       cbDepartmentType.addItem(builder.toString());
}

private class DepartmentList
{
    private int id;
    private String department;

    private DepartmentList(int id,String department)
    {
        this.id = id;
        this.department = department;
    }

    private int getId()
    {
        return id;
    }

    @Override
    public String toString() //Converting to String the (departmentId,departmentTypeList)
    {
        return department;
    }
}

我在JComboBox上添加了一个监听器来监听选择的项目。我已经将我的类转换为Object但是当我单击JComboBox时它给了我一个例外java.lang.String有什么方法可以解决这个问题吗?

if(e.getSource() == cbDepartmentType)
{
   DepartmentList item = (DepartmentList) cbDepartmentType.getSelectedItem();
   System.out.println("id "+(item.getId()));
}

堆栈跟踪:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to position.AddPosition$DepartmentList
at position.AddPosition$ItemHandler.actionPerformed(AddPosition.java:295)
at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1258)
at javax.swing.JComboBox.setSelectedItem(JComboBox.java:586)
at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:622)

更新

while(rs.next())
{
   departmentId = rs.getInt(1);
   departmentTypeList = rs.getString(2);

   ArrayList<DepartmentList> listDepartment = new ArrayList<DepartmentList>();
   listDepartment.add(new DepartmentList(departmentId,departmentTypeList));
   cbDepartmentType.addItem(listDepartment.toString());
}

1 个答案:

答案 0 :(得分:2)

您要将String添加到Combobox

cbDepartmentType.addItem(builder.toString());

您尝试将所选项目投射到DepartementList

DepartmentList item = (DepartmentList) cbDepartmentType.getSelectedItem();

但你得到一个字符串。所以这样的事情就是试着跑。

DepartmentList item = (DepartmentList) "A string";

您可以直接将DepartmentList添加到comboxbox。

cbDepartmentType.addItem(departement);

这将使用DepartementList的toString()的实现来打印组件中的文本。

这样,selectedItem将成为DepartementList的一个实例。

以下是Lucas-Lehmer test

的官方教程

编辑:

您的代码应如下所示:

while(rs.next())
{
        departmentId = rs.getInt(1);
        departmentTypeList = rs.getString(2);

        DepartmentList dep = new DepartmentList(departmentId,departmentTypeList); //Create a department
       cbDepartmentType.addItem(dep ); //insert into the combo
}

在原始代码中,您使用List来存储实例,然后恢复此实例以将其解析为StringBuilder,然后将此代表(String)插入组合框中。

我的逻辑

  

部门 - &gt;组合框

你的

  

列表&gt; Departemnt&gt; StringBuilder&gt;组合框

尝试理解你的while循环,你会发现这根本不是逻辑。