String []到Object [] Java

时间:2014-01-23 22:33:41

标签: java jtable jcombobox japplet

是否有将String[]转换为Object[]的解决方法?使用它时我一直收到错误。 我正在尝试插入jTable,但我错误地说我正在尝试将类型String转换为Object类型...

我在这里获取日期并将其插入对象月份。

    // Create calendar and format to first sunday of the year.
    Calendar c;
    Object[] months = new String[52];
    c = Calendar.getInstance();
    c.set(Calendar.MONTH,0);
    c.set(Calendar.DATE, 5);
    // Format Date and insert into months object array
    DateFormat df = new SimpleDateFormat("MM/dd/yyy");
    for (int i =0; i < 52; i++){
        months[i] = df.format(c.getTime());
        c.add(Calendar.DATE, 7);
    }

    //Insert Months array into jComboBox
    jComboBox1.setModel(new DefaultComboBoxModel(months));
    ...
    ...

    //Action performed retrieves selection from jComboBox and insert into table

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           

        // object[] o gets selection from selectedItem()
        Object[] o = (Object[]) jComboBox1.getSelectedItem();

        //error checking to println
        System.out.println(jComboBox1.getSelectedItem() + "    ");

        // create DefaultTableModel and insert into row zero with the object selected
        DefaultTableModel model = (DefaultTableModel) weeklyCalendar.getModel();

        //insert into row, throws error
        model.insertRow(0, o);
    }

soo我想我正在从getSelectedItem()获取一个字符串并尝试将其转换为Object[]并抛出错误异常...我该怎么做以解决这个问题?

3 个答案:

答案 0 :(得分:1)

如果你想要一个数组,请使用jComboBox1.getSelectedObjects()

虽然String不是必需的,但是当执行此行时,您可能希望在返回的Object上调用.toString(),以防您碰巧存储非String的对象。

//error checking to println
System.out.println(jComboBox1.getSelectedItem() + "    ");

请注意,.getSelectedObjects()方法不是首选方法,因为它仍然只返回Object []数组中的单个元素。如果你需要一个数组,那么使用.getSelectedItem()会更容易,并在事后将结果存储在数组中。

*编辑以反映评论反馈。

答案 1 :(得分:0)

您无法将完整的String数组转换为Object Array。您必须单独投射元素。创建一个方法,将String类型的所有元素强制转换为Object。

答案 2 :(得分:0)

这两条重要的路线在这里:

jComboBox1.setModel(new DefaultComboBoxModel(months));

Object[] o = (Object[]) jComboBox1.getSelectedItem();

由于String[]返回单个项目,因此您不是试图将Object[]转换为String而是将Object[]转换为getSelectedItem。< / p>

我相信你想要的只是这个:

Object o = jComboBox1.getSelectedItem();

或者这将是一个有效的演员:

String s = (String)jComboBox1.getSelectedItem();