如何添加到数组列表
问题描述:
我正在从csv文件中读取项目,然后使用StringTokenizer将元素截断并将它们放入JLabels中。到目前为止,我已经放弃了这部分。我有按钮滚动浏览每个位置,但我不确定如何输入字段并将其添加到数组中?如何添加到数组列表
这是我的计划的主要部分至今
// program reads in csvfile.
private void loadCarList() {
try{
BufferedReader CSVFile = new BufferedReader(new FileReader("car.txt"));
String dataRow = CSVFile.readLine();
while(dataRow != null){
carList.add(dataRow);
dataRow = CSVFile.readLine();
}
}catch(Exception e){
System.out.println("Exception while reading csv file: " + e);
}
}
}
//this will click cycle through the elements in the Jlabels.
private void loadNextElement(){
try {
StringTokenizer st = new StringTokenizer((String)carList.get(position), ",");
while(st.hasMoreTokens() && position <= carList.size() -1) {
position ++;
String CarID = st.nextToken();
String DealerShipID = st.nextToken();
String ColorID = st.nextToken();
String Year = st.nextToken();
String Price = st.nextToken();
String Quantity = st.nextToken();
tCarID.setText(CarID);
tDealerShip.setText(DealerShipID);
tColor.setText(ColorID);
tYear.setText(Year);
tPrice.setText(Price);
tQuantity.setText(Quantity);
}
} catch(Exception e){
JOptionPane.showMessageDialog(null, "youve reached the end of the list");
}
}
有没有在那里我可以只需键入我已经奠定了的JLabel,并添加到阵列上更简单的方法?
我有点迷失在这一点上,我不确定如何进一步与此。
答
你的问题似乎是你想在一个班级内做太多事情。这是可能的,但组织得不是很好。
创建一个单独的课程来保存单个汽车记录。它应该是简单的“bean”或“POJO”类,通常由一些私有属性和公共getter和setter(aka访问器和mutators)组成。您的汽车列表将由这些对象组成。
public class Car {
private String carID;
...
private Integer quantity;
public getCarID() {
return this.carID;
}
...
public setQuantity(Integer quantity) {
this.quantity=quantity;
}
}
定义您的汽车的列表作为当前类的属性,每一次你添加一个车到你的列表中,从你的车类构造它。
Car car=new Car();
car.setCarID(st.nextToken());
...
car.setQuantity(Integer.valueOf(st.nextToken()));
this.carList.add(car);
样式注释:不要大写非类的事物的名称。它混淆了读者(以及语法荧光笔)。 – Taymon 2012-04-08 02:50:45
对不起,但我不能告诉你在问什么。清单的确切位置,以及您想要追加的内容? – Taymon 2012-04-08 02:57:03