Hello,

I want to use a JTable for displaying data loaded from a .txt file. The problem is that I don't see any methods for inserting a row.

The code NetBeans generates is this:

jScrollPane1 = new javax.swing.JScrollPane();
        tabel = new javax.swing.JTable();
        label1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        tabel.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "column1", "column2", "column3", "column4"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };

From what I googled, to be able to insert a row, I should have something like this:

DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);

// Create a couple of columns
model.addColumn("Col1");
model.addColumn("Col2");

// Create the first row
model.insertRow(0, new Object[]{"r1"});

// Insert a row so that it becomes the first row
model.insertRow(0, new Object[]{"r2"});

// Insert a row at position p
int p = 2;
model.insertRow(p, new Object[]{"r3"});

How can I work around this? I want to be able to use the Design manipulator for moving my JTable around so I'm trying to avoid coding it by hand.

DefaultTableModel tableModel = new javax.swing.table.DefaultTableModel();
     tabel.setModel(tableModel);
        

     tableModel.insertRow(0, new Object[]{ "a", "b", "c", "d"});

Why doesn't this work?

... because I hadn't added any columns.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.