[java] How do I populate a JComboBox with an ArrayList?

I need to populate a JComboBox with an ArrayList. Is there any way to do this?

This question is related to java swing arraylist jcombobox

The answer is


By combining existing answers (this one and this one) the proper type safe way to add an ArrayList to a JComboBox is the following:

private DefaultComboBoxModel<YourClass> getComboBoxModel(List<YourClass> yourClassList)
{
    YourClass[] comboBoxModel = yourClassList.toArray(new YourClass[0]);
    return new DefaultComboBoxModel<>(comboBoxModel);
}

In your GUI code you set the entire list into your JComboBox as follows:

DefaultComboBoxModel<YourClass> comboBoxModel = getComboBoxModel(yourClassList);
comboBox.setModel(comboBoxModel);

i think that is the solution

ArrayList<table> libel = new ArrayList<table>();
try {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
s.beginTransaction();

String hql = "FROM table ";

org.hibernate.Query query = s.createQuery(hql);
libel= (ArrayList<table>) query.list();
Iterator it = libel.iterator();
while(it.hasNext()) {
table cat = (table) it.next();

cat.getLibCat();//table colonm getter


combobox.addItem(cat.getLibCat());
}
s.getTransaction().commit();
s.close();
sf.close();
} catch (Exception e) {
System.out.println("Exception in getSelectedData::"+e.getMessage());

Elegant way to fill combo box with an array list :

List<String> ls = new ArrayList<String>(); 
jComboBox.setModel(new DefaultComboBoxModel<String>(ls.toArray(new String[0])));

I don't like the accepted answer or @fivetwentysix's comment regarding how to solve this. It gets at one method for doing this, but doesn't give the full solution to using toArray. You need to use toArray and give it an argument that's an array of the correct type and size so that you don't end up with an Object array. While an object array will work, I don't think it's best practice in a strongly typed language.

String[] array = arrayList.toArray(new String[arrayList.size()]);
JComboBox comboBox = new JComboBox(array);

Alternatively, you can also maintain strong typing by just using a for loop.

String[] array = new String[arrayList.size()];
for(int i = 0; i < array.length; i++) {
    array[i] = arrayList.get(i);
}
JComboBox comboBox = new JComboBox(array);

Check this simple code

import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JFrame;


public class FirstFrame extends JFrame{

    static JComboBox<ArrayList> mycombo;

    FirstFrame()
    {
        this.setSize(600,500);
        this.setTitle("My combo");
        this.setLayout(null);

        ArrayList<String> names=new ArrayList<String>();   
        names.add("jessy");
        names.add("albert");
        names.add("grace");
        mycombo=new JComboBox(names.toArray());
        mycombo.setBounds(60,32,200,50);
        this.add(mycombo);
        this.setVisible(true); // window visible
    }   

    public static void main(String[] args) {

        FirstFrame frame=new FirstFrame();  

    }

}

DefaultComboBoxModel dml= new DefaultComboBoxModel();
for (int i = 0; i < <ArrayList>.size(); i++) {
  dml.addElement(<ArrayList>.get(i).getField());
}

<ComboBoxName>.setModel(dml);

Understandable code.Edit<> with type as required.


I believe you can create a new Vector using your ArrayList and pass that to the JCombobox Constructor.

JComboBox<String> combobox = new JComboBox<String>(new Vector<String>(myArrayList));

my example is only strings though.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to swing

Calling another method java GUI Read input from a JOptionPane.showInputDialog box Call japplet from jframe Java JTable getting the data of the selected row What does .pack() do? How to add row of data to Jtable from values received from jtextfield and comboboxes How can I check that JButton is pressed? If the isEnable() is not work? Load arrayList data into JTable How to draw a circle with given X and Y coordinates as the middle spot of the circle? Simplest way to set image as JPanel background

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable

Examples related to jcombobox

Adding items to a JComboBox Execute an action when an item on the combobox is selected How to set selected index JComboBox by value How do I populate a JComboBox with an ArrayList? JComboBox Selection Change Listener?