I want to be able to define the columns and data at a later point in the code instead of immediately in the constructor method, is there a way to do this?
Use a TableModel
To manage the data. See the "default" implementation DefaultTableModel
. At any time you can use JTable#setModel
and pass new TableModel
.
JTable table = new JTable();
...
// Some time later
String[] headers = ...
Object[][] data = ...
DefaultTableModel model = new DefaultTableModel();
table.setModel(model);
Or you can create the table with the model, and at whatever time, call the model's methods, like (in the case of DefaultTableModel
), setColumnIdentifiers
, addRow
, setDataVector
String[] headers = ...
DefaultTableModel model = new DefaultTableModel(headers, 0);
JTable table = new JTable(model);
...
// Some time later
Object[] row = ...
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.addRow(row);
String[] newHeaders = ...
model.setColumnIdentifiers(newHeaders);
"Also, is there a way to convert a dimensional array list into a 2 dimensional object array so I can use it in the JTable?"
I've never heard the term "dimensional array list". But if you want to add an ArrayList<String>
as a row, you can simply call list.toArray
and add a row to the DefaultTableModel
. If it's an ArrayList<YourType>
, you may need to create a custom table model implementation. (See the link below)
See for more info:
> into an object[][], for purposes of putting it into the JTable. (and I meant to say "2 dimensional array list", missed the 2, still not sure if that's an actual term though).
– user2908849 Mar 06 '15 at 19:05