博为峰小博老师:
创建一个继承DefaultListModel的类来创建一个列表框。其具体的程序代码如下所示:
publicclassBWF {
publicstaticvoidmain(String[]args) {
JFramejf=newJFrame("博为峰教育");
ContainercontentPane=jf.getContentPane();
ListModelmode=newDataModel();
JListlist=newJList(mode);
list.setVisibleRowCount(5);
list.setBorder(BorderFactory.createTitledBorder("电脑配件"));
contentPane.add(newJScrollPane(list));
jf.pack();
jf.setVisible(true);
jf.addWindowListener(newWindowAdapter() {
publicvoidwindowClosing(WindowEvente) {
System.exit(0);
}
});
}
}
classDataModelextendsDefaultListModel{
String[]s={"主板","显示器","内存","CPU","硬盘","电源","键盘","鼠标","显卡"};
publicintgetSize() {
returns.length;
}
publicStringgetElementAt(intindex) {
return(index+1)+"."+s[index++];
}
}