Search code examples
javajtablejcomboboxjapplet

String[] to Object[] Java


Is there a workaround for casting a String[] to Object[]? I keep getting an error when using this. I am trying to insert into a jTable and it gives me error saying I am trying to convert type String to type Object...

Here I am getting dates and inserting it into object months.

    // 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 I guess I am getting a string from getSelectedItem() and trying to cast it to an Object[] with throws the error exception...what can I do to get around that?


Solution

  • Use jComboBox1.getSelectedObjects() instead if you want an array.

    Though not necessary for String, you may want to call .toString() on the returned Object when this line executes, just in case you happen to be storing Objects that are not String.

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

    Note that the .getSelectedObjects() method wouldn't be the preferred one to use, as it's still only returning a single element in an Object[] array. If you need an array, it would be easier just to use .getSelectedItem() and store the result in an array after the fact.

    *Edited to reflect comment feedback.