user2908849
user2908849

Reputation: 77

JTable updating in run time

Is there a way to update a JTable during run time and without using the constructor?

I have a JTable that I have already added to my JPanel but 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?

JPanel jp = new JPanel();
JTable table = new JTable();
jp.add(table);

Also, is there a way to convert a 2 dimensional array list into a 2 dimensional object array so I can use it in the JTable?

Upvotes: 0

Views: 1545

Answers (3)

Paul Samsotha
Paul Samsotha

Reputation: 208944

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:

Upvotes: 3

rob
rob

Reputation: 6247

Yes, you can set the table's contents at runtime. see JTable.setModel(TableModel)

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'm not sure what you mean by "dimensional array list" but you can either convert the data structure to a standard TableModel implementation like DefaultTableModel , or write a wrapper class that implements the TableModel interface. The wrapper class would read data directly from your data structure and expose its elements to the JTable via the methods defined in TableModel.

Upvotes: 1

mr.icetea
mr.icetea

Reputation: 2637

You can use addRow method of DefaultTableModel to add data to table, at runtime. And use fireTableDataChanged to notify your JTable to update it's UI. Document here

Upvotes: 0

Related Questions