0

我正在开发一个从 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");
    }
}

有没有一种更简单的方法,我可以输入我布置的 jlabels 并添加到数组中?

在这一点上我有点迷茫,我不确定如何进一步处理。

4

1 回答 1

0

您的问题似乎是您试图在一堂课内做太多事情。可以这样做,但组织得不是很好。

创建一个单独的类来保存单个 Car 记录。它应该是简单的“bean”或“POJO”类,通常由一些私有属性和公共 getter 和 setter(也称为访问器和修改器)组成。您的汽车列表将由这些对象组成。

public class Car {
  private String carID;
  ...
  private Integer quantity;

  public getCarID() {
     return this.carID;
  }
  ...
  public setQuantity(Integer quantity) {
    this.quantity=quantity;
  }
}

将您的 Cars 列表定义为当前类的属性,并且每次将 Car 添加到列表中时,从 Car 类中构造它。

Car car=new Car();
car.setCarID(st.nextToken());
...
car.setQuantity(Integer.valueOf(st.nextToken()));
this.carList.add(car);
于 2012-04-08T04:07:00.693 回答