Reputation: 901
String[] columnNames = {"Type", "Employee ID", "First/Last Name","DOB", "Gender", "HIre Date", "OnCall", "BaseSalary", "Commission/Hourly Rate"};
Object[][] data = new Object[10][9];
table = new JTable(data,columnNames);
public ArrayList<Person> employeeList = new ArrayList<Person>();
public ArrayList<Client> clientList = new ArrayList<Client>();
public ArrayList<Stock> stockList = new ArrayList<Stock>();
I'm trying to create a JTable with information inside a array-list. I tried something along the lines of.
data[0][0] = "Account";
data[0][1] = 1; //int
data[0][2] = "Name";
data[0][3] = dob; //Date class
data[0][4] = gender; //Enum
data[0][5] = hire //Date class
data[0][6] = true; //boolean
data[0][7] = 125.23; //double
data[0][8] = 0.015; //double
Which didn't work out really well, I try google but most of the examples have pre-made arrays so didn't help much.
Upvotes: 0
Views: 3011
Reputation: 28598
The JTable model documentation is confusingly in it's simplistic explanations. It's almost always a mistake to pass in data to the table constructor. You should implement your own table model that is derived form AbstractTableModel, and pass that model object into the constructor for the table.
Then your table model, can just have a private member variable like
public ArrayList<Person> employeeList = new ArrayList<Person>();
then you just need to implement a few methods, like
public int getRowCount() {
return emplyeeList.size();
}
and such as
public Object getValueAt(int rowIndex, int columnIndex) {
Person p = employeeList.get(rowIndex);
switch (columnIndex) {
case 1:
return p.getName();
....
}
}
etc.
It makes your programming much simpler as the model uses your natural data structures to hold the data.
Upvotes: 1
Reputation: 7344
I think your problem is with the data array. Arrays in java are not dynamic. Defining
Object[][] data = {};
you are creating an array of length 0.
You'd have to be able to know their lengths beforehand and use them in the creation or use the List's toArray method.
Upvotes: 1