Search code examples
javaswingarraylistjcombobox

Showing list of what's in ArrayList


I have a problem getting my JComboBox's drop down list to show a list of hotels by hotel name.

My ArrayList contains hotelNo, hotelName, city.

In my GUI, ive written this

 Object[] hotelArr = { databaseconn.arrayListHere() };
    @SuppressWarnings({ "rawtypes", "unchecked" })
    // this just hide some unimportant warnings
    JComboBox hotelList = new JComboBox(hotelArr);
    hotelList.addActionListener(this);
    frame.add(hotelList, BorderLayout.NORTH); 

I can click the drop down list but it only shows "[]". Brackets I think they're called. I want it to show the list of hotelName which is also stored in the ArrayList hotelInfo I've put in a method called arrayListHere.

So how do I do it? Spent many hours on this issue. Couldn't find an answer or help anywhere. I also checked the docs but didn't get anything I could use.


Solution

  • The way your Object[] hotelArr is defined was incorrect. Also, it's not possible to simply cast a list to an array. Instead, you must convert the list to a data structure, the JComboBox can handle. There are several posibilities:


    1. (best in my opinion, because:

    • guarantees type safety, if you are handling classes other than Object
    • return type of arrayListHere() can be the interface Collection, which makes it more common, than a returned List

    Collection<E> list = databaseconn.arrayListHere();
    Vector<E> vector = new Vector(list);
    JComboBox box = new JComboBox(vector);
    

    2. if you stay with List as return type of arrayListHere()

    Object[] array = databaseconn.arrayListHere().toArray();
    JComboBox box = new JComboBox(array);