Link to home
Start Free TrialLog in
Avatar of chenwei
chenwei

asked on

How to add rows to a JTable dynamically?

In my program I will add rows to a JTable dynamically. My codes look like follows:

...
...
private javax.swing.JTable jTable = null;
...
private javax.swing.JTable getJTable() {
  if(jTable == null) {
    jTable = new javax.swing.JTable();
  }
  return jTable;
}
...
...
for(int i= 0; i<5; i++)
  jTable.addColumn(new javax.swing.table.TableColumn(i,15));  // the table has 5 columns
...
...
// now I will read data from a file and insert into the table.
try{
  BufferedReader in = new BufferedReader(new FileReader(tableFileName));
  String line;
  while((line = in.readLine()) != null)
  {
     // here a row will be added to jtable;
  }
...
...
            
ASKER CERTIFIED SOLUTION
Avatar of zzynx
zzynx
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Assuming that your file is a CSV file containing the column data:
E.g.  column1Data,column2 Data,Data3,Data4,Data5

while((line = in.readLine()) != null) {
     model.addRow( line.split(",") );
}
Avatar of rohanbairat3
rohanbairat3

You can use DefaultTableModel or write your own model. It is very easy. These models identify the change by itself and would update the JTable automatically. You dont have to worry abt forcing the updates
Avatar of chenwei

ASKER

To zzynx:

Thanks, it works. But How can I set the table cell non-editable?
That's another Q isn't it?

>>How can I set the table cell non-editable?
Use your own TableModel (extending DefaultTableModel).

and overwrite the function

  boolean isCellEditable(int row, int column) {
      if (column==1)
         return false;   // makes the 2nd column non-editable
      return true;
  }
Thanks for accepting