JTable在arrayList中显示数据

时间:2013-12-02 20:32:02

标签: java eclipse swing arraylist jtable

在Java Eclipse中进行编码。制作预订系统。我们的想法是从数据库中获取信息,将其存储在ArrayList中,并从ArrayList中通过JTable将其显示在GUI中。最后一部分有一些问题,只是无法搞清楚.. ArrayList的:

import java.util.ArrayList;

public class CarList
{
   private ArrayList<Car> cars;

   public CarList()
   {
      cars = new ArrayList<Car>();
   }

   public int getNumberOfCars()
   {
      return cars.size();
   }

   public Car getCar(String CarMake)
   {
      for (int i = 0; i < cars.size(); i++)
      {
         if (cars.get(i).getMake() == CarMake)
         {
            return cars.get(i);
         }
      }
      return null;
   }

   public int size()
   {
      return cars.size();
   }

   public void add(Car car)
   {
      if (!this.ModelExists(car.getModel()))
      {
         cars.add(car);
      }

   }

   public Boolean ModelExists(String Model)
   {

      for (Car c : cars)
      {
         if (c.getModel().equals(Model))
         {
            return true;
         }
      }
      return false;
   }

   public void remove(String CarMake)
   {
      for (int i = 0; i < cars.size(); i++)
      {
         if (cars.get(i).getMake() == CarMake)
         {
            cars.remove(i);
         }
      }

   }

   public String toString()
   {
      String returnStr = "";

      for (int i = 0; i < cars.size(); i++)
      {
         Car temp = cars.get(i);

         returnStr += temp + "\n";
      }
      return returnStr;
   }


}

从数据库获取数据到arraylist的适配器:

public CarList getAllCars()
   {
      MyDatabase myDB = new MyDatabase();
      CarList cars = new CarList();
      try
      {
         myDB.openMySQLDatabase("db", "root", "");

         String sql = "SELECT Make, Model, LicenseNumber, Color, Year," +
                "HorsePower, TimeUntilService, ConsumptionPerKm," +
                "NumberOfSeats, NumberOfDoors, Transmission, ClimateControl,Price "
               + "FROM cars";
         System.out.println(sql);
         Object[][] result = myDB.returnSQLQueryResult(sql);

         for (int rows = 0; rows < result.length; rows++)
         {
            System.out.println("result row");
               String make = (String) result[rows][0];
               String model = (String) result[rows][1];
               String licenseNumber = (String) result[rows][2];
               String color = (String) result[rows][3];
               int year =  (int) result[rows][4];
               String horsePower = (String) result[rows][5];
               String timeUntilService = (String) result[rows][6];
               String consumptionPerKm = (String) result[rows][7];
               int numberOfSeats = (int) result[rows][8];
               int numberOfDoors = (int) result[rows][9];
               String transmission = (String) result[rows][10];
               String climateControl = (String) result[rows][11];
               int price = (int) result[rows][12];

               cars.add(new Car(make, model, licenseNumber, color, year, horsePower, 
                     timeUntilService, consumptionPerKm,  climateControl, numberOfSeats, numberOfDoors, transmission, climateControl, price));


         }
      }
      catch (SQLException e)
      {
         e.printStackTrace();
      }
      catch (ClassNotFoundException e)
      {
         e.printStackTrace();
      }
      finally
      {
         try
         {
            myDB.closeDatabase();
         }
         catch (SQLException e)
         {
            e.printStackTrace();
         }
      }
      System.out.println(cars.size());
      return cars;
   }

的JTable:

panelBottomRight = new JPanel();
      panelBottomRight.setLayout(new BorderLayout());
      panelBottomRight.setBorder(new TitledBorder(BorderFactory
            .createLineBorder(Color.black), "[Cars]", 2, 0));

      tableBottomRightCenter = new JPanel();
      tableBottomRightCenter.setLayout(new BorderLayout());

      String[] columnNames = { "Make", "Model", "LicenseNumber", "Color",
            "Year", "HorsePower", "TimeUntilService",
            "ConsumptionPerKm", "NumberOfSeats", "NumberOfDoors",
            "ClimateControl" };
      CarList cars= new CarList();
      String[][] data = {};

      // Create table with database data
      tableBottomR = new JTable(data, columnNames);

      tableBottomR.setAutoCreateRowSorter(true);
      tableBottomR.getTableHeader().setReorderingAllowed(false);
      tableBottomR.setModel(new DefaultTableModel(data, columnNames)

      {
         @Override
         public boolean isCellEditable(int rowIndex, int columnIndex)
         {
            return false;
         }
      });

      tableBottomRightCenter.add(tableBottomR, BorderLayout.CENTER);

      scrollPane2 = new JScrollPane(tableBottomR);
      scrollPane2
            .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

      tableBottomRightCenter.add(scrollPane2);

      panelBottomRight.add(tableBottomRightCenter, BorderLayout.CENTER);

1 个答案:

答案 0 :(得分:2)

有一些事情会跳出来。

在您CarList中,getCar方法正在比较对象引用,而不是比较String的内容

对于String比较,您应该使用String#equals,例如......

public Car getCar(String CarMake) {
    for (int i = 0; i < cars.size(); i++) {
        //if (cars.get(i).getMake() == CarMake) {
        if (cars.get(i).getMake().equals(CarMake)) {
            return cars.get(i);
        }
    }
    return null;
}

您似乎没有使用getAllCars方法填充表模型,而只是创建一系列空表模型。

就个人而言,我不是DefaultTableModel的粉丝,特别是考虑到你有一个Car对象和CarList对象,我会要求你将所有这些工作撤消到使用它,相反,我更喜欢创建我自己的,专门的,实现,这允许我提供更好的控制,例如......

public class CarModel extends AbstractTableModel {

    private String[] columnNames = { "Make", "Model", "LicenseNumber", "Color",
        "Year", "HorsePower", "TimeUntilService",
        "ConsumptionPerKm", "NumberOfSeats", "NumberOfDoors",
        "ClimateControl" };

    private CarList carList;

    public CarModel(CarList list) {
        carList = list;
    }

    public CarList getCarList() {
        return carList;
    }

    @Override
    public int getRowCount() {
        return getCarList().getNumberOfCars();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public String getColumnName(int column) {
        return columnNames[column];
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        Class type = String.class;
        switch (columnIndex) {
            case 0:
                type = String.class;
                break;
            // ...etc...
        }
        return type;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Car car = getCarList().getCarAt(rowIndex);
        Object value = null;
        switch (columnIndex) {
            case 0:
                value = car.getMake();
                break;
            //...etc...
        }
        return value;
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false;
    }             
}

这显然需要您向getCarAt(int)添加CarList方法,以便在给定索引处返回Car

然后,您只需从数据库中提取数据并将生成的CarList应用于表模型,例如......

CarList carList = getAllCars();
CarTableModel model = new CarTableModel(carList);

然后,您只需将其添加到您的UI中,例如......

JTable table = new JTable(model);
add(new JScrollPane(table));

请查看How to use tables了解更多详情和示例......