我的学校是另一堂课的一系列学校课程。
我不能在我的生活中添加并在JList中显示这个数组。
public class SchoolChooser extends JPanel {
private School[] schools;
有任何帮助吗? 三江源。
答案 0 :(得分:2)
在tutorial中阅读有关JList的更多信息。
这是一个简单的例子。我将JList
与DefaultListModel
和自定义渲染器一起使用DefaultListCellRenderer
。我写了自己的学校课程,由你自己替换。
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();
}
}
我的School
课程:
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;
}
}
结果: