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