简体   繁体   中英

Displaying collection in jlist

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.

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:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM