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

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

问题描述

在此处使用 Java Eclipse 进行编码.制作预约系统.这个想法是从数据库中获取信息,将其存储在 ArrayList 中,然后从 ArrayList 通过 JTable 在 GUI 中显示它.最后一部分有一些问题,只是无法弄清楚..数组列表:

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


}

从db获取数据到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;
    }             
}

显然,这将要求您将 getCarAt(int) 方法添加到您的 CarList 以返回给定索引处的 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天全站免登陆