0

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);
4
  • I browsed through your code and don't see where you tried to add any data to the JTable so I assume that's what you're confused about. The JTable itself is a visual representation of an actual table. It doesn't store the data itself, but a, shall we say, TableModel (which you added a DefaultTableModel) that stores the data. What you should focus on doing is working with the TableModel to add data to that TableModel by taking your ArrayList and converting it into a single row of data, and inserting that data into the TableModel. stackoverflow.com/questions/295649/adding-rows-to-a-jtable Commented Dec 2, 2013 at 20:36
  • please 1. whats goal, 2. for better help sooner post an SSCCE, short, runnable, compilable, with hardcoded value for JTable instead of JDBC, 3.JTable based on String[][] isn't good idea, use 1. Vector<Vector<Object>> / AbstractTableModel based on util.List, 2. better will be search (don't reinvent the wheel) for ResultSetTableModel or TableFromDatabase` Commented Dec 2, 2013 at 20:42
  • @Compass Followed your advice and made this tableBottomR = new JTable(new DefaultTableModel(new Object[]{"Make", "Model","Color", "Year", "HorsePower", "NumberOfSeats", "NumberOfDoors"})); Although , now I get errors: The constructor DefaultTableModel(Object[]) is undefined Commented Dec 2, 2013 at 20:53
  • @Fancypants try this tutorial, it'll better explain it than I can put into this blob docs.oracle.com/javase/tutorial/uiswing/components/table.html Commented Dec 2, 2013 at 21:23

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

11 Comments

too much hassle just to make the data show on the tables. I am new to Java ,meaning first semester student and i just know as far as GUI (had to learn JTable by myself) arraylists inheritance and all that. This seem too complicated for my blood, is there any other way to do this? Because I simply won't manage it this way. Unless you want to give me private online Java lessons , lol. But thank you for your solution it is still something :)
Really? Because you have about 90% of the work already done. To make it work with DefaultTableModel you will need to undo much of work you have done with CarList and Car, which IMHO seems like a lot more work then the benefit you will gain from it.
Ok, let's say I try this. So basically the class you've supplied (for which I'm very thankful) works as a table model?
Yes, basically, DefaultTableModel extends from AbstractTableModel which implements TableModel, so basically, I've jumped in where DefaultTableModel would sit, but provided a much more customised solution...
Also, JTable works best when it's contained within in a JScrollPane
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.