Maydayfluffy
Maydayfluffy

Reputation: 427

List<Integer> error

First I put in...

List<int> age = new ArrayList<int>();
     for (int i = 1; i <= 100; ++i) {
     age.add(i);
     }
JComboBox ageComboBox = new JComboBox(age);

The error I got was...syntax error on token int dimensions expected after this token...on the two 's.

So after taking suggestions provided by Eclipse I got...

ArrayList<Integer> ageList = new ArrayList<Integer>();

for (int i = 1; i <= 100; ++i) {
ageList.add(i);
}

JComboBox<ArrayList<Integer>> ageEntries = new JComboBox<ArrayList<Integer>>(ageList);

Why can't I put in the ageList into the JComboBox?

Error:The constructor JComboBox>(ArrayList) is undefined

Upvotes: 0

Views: 2368

Answers (3)

Maarten Blokker
Maarten Blokker

Reputation: 604

You are creating a combobox wich has ArrayList as elements. Im guessing you just want to add the integers, so use the type Integer directly. Then you pass ageList, wich is an ArrayList in the constructor.

There are a few constructors in jcombobox:

  • JComboBox()
  • JComboBox(Vector items)
  • JComboBox(E[] items)
  • JComboBox(ComboBoxModel aModel)

None of wich can be used for what you are trying to do, ageList is not a vector, or an array, its an ArrayList.

If you are trying to add the list of integers to the combobox, i suggest you create a new model and add all your integers to it. Then assign the model to the combobox, like this:

DefaultComboBoxModel<Integer> model = new DefaultComboBoxModel<Integer>();
for (Integer i : ageList) {
    model.addElement(i);
}

JComboBox<Integer> ageEntries = new JComboBox<Integer>();
ageEntries.setModel(model);

Upvotes: 0

Alistair A. Israel
Alistair A. Israel

Reputation: 6567

According to the documentation JComboBox only has a default constructor, one that accepts a ComboBoxModel, an array, and a Vector:

JComboBox() 
JComboBox(ComboBoxModel aModel) 
JComboBox(Object[] items) 
JComboBox(Vector<?> items) 

An Arraylist is not a Vector (and neither is a List, though a Vector is a List).

Anyway, so a quick fix might go something like:

new JComboBox(ageList.toArray(new Integer[]));

Just realized, you're probably on Java 7 where JCombobox is parameterized. However, the type paramater to the JCombobox should be the type of the elements of the collection—not the collection itself. But my quick fix should still work.

IOW,

JComboBox<Integer> ageEntries = new JComboBox<Integer>(ageList.toArray(new Integer[]));

Upvotes: 2

Irfy
Irfy

Reputation: 9587

Try it with Vector<Integer>, and do not parametrize the JComboBox. See also the documentation

The documentation says that JComboBox is not parametrized and that it has the constructor JComboBox(Vector<?> items) (among others, where this one is the best match for you).

Upvotes: 0

Related Questions