FancyPants
FancyPants

Reputation: 93

JTable display data in 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;
   }


}

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

Upvotes: 0

Views: 2311

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347334

There are a few things that jump out.

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

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

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.

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

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

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

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...

Upvotes: 2

Related Questions