我正在尝试在没有JList
的情况下显示DefaultListModel
。我使用自己的方法add
将元素添加到JList
,但它会产生很多错误,例如
线程“AWT-EventQueue-0”中的异常java.lang.NullPointerException 在javax.swing.JList $ 4.getSize(未知来源)
如何解决?
创建JList
import laba2.ACrafts;
import laba2.List;
import javax.swing.*;
public class MyForm extends JFrame{
JFrame formShow;
private JList<ACrafts> list;
public List li;
private JButton btnAdd;
public MyForm() {
li = new List();
JPanel panelShow = new JPanel();
formShow = new JFrame("Aircrafts");
formShow.setBounds(100, 100, 700, 550);
formShow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
formShow.add(panelShow);
panelShow.setLayout(null);
list = new JList<ACrafts>();
list.setLayoutOrientation(JList.VERTICAL);
list.setBounds(20, 20, 640, 150);
ACrafts[] arr;
arr = li.toArray();
list.setListData(arr);
panelShow.add(list);
public void setData(ACrafts a) {
li.add(a);
}
}
List.java中的方法add
class Element{
Element left;
ACrafts data;
Element right;
}
public class List implements ListImpl{
private Element first;
private Element last;
private int size;
public List() {
first = null;
last = null;
size = 0;
}
public void add(ACrafts e){
Element elem = new Element();
elem.data = e;
if (size == 0)
first = last = elem;
else
last.right = elem;
elem.left = last;
last = elem;
size++;
}
}
Main
功能(设定数据)
public static void main(String[] args) {
ACrafts[] aircraft = new ACrafts[5];
aircraft[0] = new ACrafts("Boeing 767-300F","США",7130,54000,13100,850);
aircraft[1] = new ACrafts("Airbus 310-300F","Франция",39000,9600,12200,850);
aircraft[2] = new ACrafts("Boeing 757-200F","США",7100,39780,12500,935);
aircraft[3] = new ACrafts("IL-86","Украина",3300,15000,11000,950);
aircraft[4] = new ACrafts("Avro RJ-100","Великобритания",2255,9500,10600,890);
MyForm form = new MyForm();
form.setData(aircraft[0]);
form.setData(aircraft[1]);
form.setData(aircraft[2]);
form.setData(aircraft[3]);
form.setData(aircraft[4]);
form.formShow.setVisible(true);
}
ACrafts.java
public class ACrafts implements Comparable<ACrafts> {
public String name;
public String production;
public int flightRange;
public int weight;
public int flightHeight;
public int speed;
public ACrafts(String n, String pr, int fR, int w, int fH, int s){
this.name=n;
this.production=pr;
this.flightRange=fR;
this.weight=w;
this.flightHeight=fH;
this.speed=s;
}
}