Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding rows to a JTable

Tags:

java

swing

We have a simple project where we read data from a socket and we want to populate a table with the coming data, but we can't find a way to add rows to a yet created JTable object, we can only find how to add rows at creation time of the table.

Is it possible to add rows dynamically to a JTable, or there is a better alternative object to deal with this way of showing data?

EDIT: Thanks a lot for your answers.

All three of them look very promising, but I have to choose only one and I think the best is Guillaume's.

like image 326
Saiyine Avatar asked Nov 17 '08 14:11

Saiyine


People also ask

How do you add a row in Java?

To add a row: DefaultTableModel model = (DefaultTableModel) table. getModel(); model. addRow(new Object[]{"Column 1", "Column 2", "Column 3"});

How add data from Jtextfield to JTable?

To add the data entered in the JTextFields you will need to register an ActionListener to your add button, in this case jButton1 . To add entries to your table model you could use a mutable model such as DefaultTableModel : DefaultTableModel model = new DefaultTableModel(data, columns);

How add column in JTable in Netbeans?

Right-click the table and select "Properties." The table's properties display, including the columns. You click a column and change the heading to edit the current columns. To add a new column, click "New" and type a heading for the column.


2 Answers

You should create a custom TableModel. A JTable doesn't actually store the rows, it always delegates that to a TableModel. To help you implementing it, you should make use of AbstractTableModel. Don't forget to call fireTableRowsInserted() every time you add rows. For better performances if you add a lot of rows, try to batch the updates and add many rows at a time.

like image 98
Guillaume Avatar answered Oct 12 '22 07:10

Guillaume


If you use the default table model for a JTable then you can add rows with following code

 if ( dest+1 < table.getRowCount()-1 )
    ( (DefaultTableModel) table.getModel() ).insertRow(dest+1, getValuesForNewRow());
  else
    ( (DefaultTableModel) table.getModel() ).addRow(getValuesForNewRow());
like image 33
Peter Avatar answered Oct 12 '22 07:10

Peter