The Revguin The Revguin - 1 year ago 115
Java Question

Can't add a row to a jTable even when using getModel

I've been searching through this website for numerous hours now on how to get my button to an a row to an already existing table, this table created by simply clicking the swing Controls, and adding a table and altering the fields through the properties.

The table's variable name is 'table'.

And when confronted with this line of code:

table.getModel().insertRow(table.getRowCount(),new Object[]{nome[i],data[i]});

The 'insertRow' part is redded and I can't seem to fix it.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String direcdate=direc1.getText();

File folder = new File(direcdate);
File[] listOfFiles=folder.listFiles();

String[] nome = new String[250];
String[] data = new String[250];
int i=0;

for (File listOfFile : listOfFiles) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

if (listOfFile.isFile()) {

nome[i]= listOfFile.getName ();
data[i] =sdf.format(listOfFile.lastModified());


else if (listOfFile.isDirectory()) {

nome[i]= "Folder: " + listOfFile.getName ();
data[i] =sdf.format(listOfFile.lastModified());

for(int increm=0;increm<i;increm++)
table.getModel().insertRow(table.getRowCount(),new Object[]{nome[i],data[i]});



Any ideas or suggestions?

EDIT: where the table model is located:
public class GAPAC_TESTE extends javax.swing.JFrame {

public GAPAC_TESTE() {

jTextPane2.setText("Após escolher a diretoria, escolha uma das opções.");
DefaultTableModel model = new javax.swing.table.DefaultTableModel();
table = new javax.swing.JTable(model);

Answer Source

That method return a TableModel. Did you look at the API for the TableModel interface? It does not contain an insertRow(...) method.

The DefaultTableModel has the insertRow(...) method. So assuming your table is using a DefaultTableModel the code would be:

DefaultTableModel model = (DefaultTableMode)table.getModel();

Don't always write you code in a single statmentment. Break the statement up into multiple statements so you understand exactly which part of the statement causes the problem and it makes sure you assign the variable to the proper class.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download