Werneck Werneck - 3 months ago 14
Java Question

ArrayList to JList - More than one object element

I'm using Eclipse, programming in Java. The problem:

This is how I want my JList to be displayed:

1 - Dante
2 - William
3 - Jaime
etc...


Now, the numbers are the IDs of the objects, and the names are, well, the names.

ArrayList is named TraitList.

This is what I get when I put that as the "model" property in the JList from the Window Builder in Eclipse:

TraitL.setModel(new AbstractListModel() {
String [] values = new String[] {"1 - Dante", "2 - William", "3 - Jaime"};
public int getSize() {
return values.length;
}
public Object getElementAt(int index) {
return values[index];
}
});


So I changed it for:

TraitL.setModel(new AbstractListModel() {
String [] values = new String [];
for (int jln = 0; jln < TraitList.size(); jln++){
values [jln] = (TraitList.get(jln).id + " - " + TraitList.get(jln).Name);
}
public int getSize() {
return values.length;
}
public Object getElementAt(int index) {
return values[index];
}
});


It didn't work. I've tried dozens of variants. None worked. So, how do I make multiple elements of an object be displayed by this list? I don't care if it's DefaultListModel or AbstractListModel, or even ListModel.
Thanks in advance.

EDIT: Errors of all lines with what I've tried are in the following image:
errors

BONUS QUESTION:
How do I make clicking in an element of this list an "actionPerformed" so something happens after I click it?

Answer
new AbstractListModel() {
    String [] values = new String [];
    for (int jln = 0; jln < TraitList.size(); jln++){
        values [jln] = (TraitList.get(jln).id + " - " + TraitList.get(jln).Name);
    }
    public int getSize() {
        return values.length;
    }
    public Object getElementAt(int index) {
        return values[index];
    }
}

This is an invalid anonymous class definition, you've got code floating around in the class body.

It can be fixed by either moving the initialization to a private method:

String [] values = initTraitList();
private String[] initTraitList() {
    String [] values = new String [TraitList.size()];
    for (int jln = 0; jln < TraitList.size(); jln++){
        values [jln] = (TraitList.get(jln).id + " - " + TraitList.get(jln).Name);
    }
    return values;
}

or by using an instance initialisation block:

String [] values = new String [TraitList.size()];
{
    for (int jln = 0; jln < TraitList.size(); jln++){
        values [jln] = (TraitList.get(jln).id + " - " + TraitList.get(jln).Name);
    }
}