JTable在arrayList中显示数据 [英] JTable display data in arrayList

查看:93
本文介绍了JTable在arrayList中显示数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处使用Java Eclipse进行编码.进行预订系统.这个想法是从数据库中获取信息,将其存储在ArrayList中,然后从ArrayList中通过JTable在GUI中显示它.最后一部分有些问题,就是无法解决. ArrayList:

coding in Java Eclipse here. Making a booking system. The idea is to take the info from the database ,store it in the ArrayList and from the ArrayList show it in the GUI through JTable. Having some problems with the last part and just can't figure it out.. 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:

Adapter to get the data from the db to the 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);

推荐答案

有些事情跳出来了.

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

In you CarList, the getCar method is comparing object references instead of comparing the contents of the String

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

For String comparison, you should be using String#equals, for example...

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方法填充表格模型,而只是创建了一系列空表格模型.

You don't seem to be using the getAllCars method to populate the table model, but are simply creating a series of empty table models.

就我个人而言,我不是DefaultTableModel的粉丝,特别是考虑到您有Car对象和CarList对象的事实,我要求您撤消所有这些工作才能使用它,相反,我宁愿创建自己的,专门的实现,也可以让我提供更大的控制权,例如...

Personally, I'm not a fan of DefaultTableModel, especially given the fact that you have a Car object and CarList object, i would require you to undo all this work to use it, instead, I prefer to create my own, specialised, implementation, which allows me to provide greater control, for example...

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;
    }             
}

很明显,这将要求您在CarList中添加getCarAt(int)方法,以在给定索引处返回Car.

This, obviously, will require you to add a getCarAt(int) method to your CarList to return the Car at the given index.

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

Then, you simply need to extract the data from the database and apply the resulting CarList to the table model, for example...

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

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

Then, you just need to add it to your UI, for example...

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

请参阅如何使用表以了解更多信息详细信息和示例...

Take a look at How to use tables for more details and examples...

这篇关于JTable在arrayList中显示数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆