I'm working in NetBeans on a Java Project.
I need to display every State
(e.g. "Oklahoma") in an ArrayList<State>
in a JList
.
I can't figure out how to do this... especially not in NetBeans.
I think it involves creating a DefaultListModel
with each State
as a String
. I've tried this a million different ways to no avail.
Is it possible to just load the ArrayList<State>
(perhaps if the State
class has a toString()
method)? This would be especially helpful, because I could directly modify the ArrayList<State>
via actionPerformed()
.
For the sake of the question, let's assume a State
is an object with a name
of type String
and a population
of type int
.
I hope this makes sense.
Thanks.
Unfortunately, the only 'easy' initialization of JList with a List is via Vector
All these answers are great, and certainly useful. I ended up solving it very simply from the controller:
view.getStatesList().setListData(model.getStates().toArray());
The key is the use of
.setListData()
(which can take an Array as an argument) instead of.setModel()
.I presume your talking about the Matisse GUI builder here, otherwise this should be fairly trivial.
First off you need to create the custom ListModel
in the constructor of your class initialise the ListModel before initComponents() is called, and make it a field not a local variable.
In the NetBeans GUI builder right click on your JLIst, and select 'customize code'. You will see something along the lines of jList1.setModel(...) Change the dropdown to custom property and edit the code to read
All answers provided here are great (+1). In my opinion you will be best creating your own model which you can later reuse easily knowing how it works.
And here you have a very simple use example.
I recommend it for you to have such a model always somewhere, e.g. in a utility package, available and ready to use. You will see how often such simple model you will find useful. This one is perfect for displaying any type of data.
All the best, Boro.
The easiest solution is to create a DefaultListModel and then iterate through the ArrayList adding your State objects into the list model as you go. Then use this model as the model of your JList. If on the other hand you want to use the ArrayList in the model, then you'll likely need to create a class that extends AbstractListModel class, but be ready to have to flesh out more of the methods of this class for it to work well.