Reputation: 1
I have schools which is an array of school objects in abother class.
I cant for the life of me add and display this array in a JList.
public class SchoolChooser extends JPanel {
private School[] schools;
Any help? Thankyou.
Upvotes: 0
Views: 1111
Reputation: 10994
Read more about JList in tutorial.
Here is simple example for you. I use JList
with DefaultListModel
and custom renderer based on DefaultListCellRenderer
. I wrote my own School class replace it by yours .
class Example extends JFrame {
private DefaultListModel<School> model;
private School[] schools;
public Example() {
schools = new School[]{
new School("test1",1),
new School("test2",2),
new School("test3",3),
};
JList<School> list = new JList<>(model = new DefaultListModel<>());
for(School school : schools){
model.addElement(school);
}
list.setCellRenderer(getCellRenderer());
add(new JScrollPane(list));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private ListCellRenderer<? super School> getCellRenderer() {
return new DefaultListCellRenderer(){
@Override
public Component getListCellRendererComponent(JList<?> list,
Object value, int index, boolean isSelected,
boolean cellHasFocus) {
School s = (School) value;
Component listCellRendererComponent = super.getListCellRendererComponent(list, s.getNumber()+"/"+s.getName(), index, isSelected,cellHasFocus);
return listCellRendererComponent;
}
};
}
public static void main(String...strings ){
new Example();
}
}
My School
class:
public class School {
private String name;
private Integer number;
public School(String name, Integer number){
this.setName(name);
this.setNumber(number);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
}
and the result:
Upvotes: 2