954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Netbeans JTable insert Row

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.

Buffalo101
Junior Poster
116 posts since Oct 2009
Reputation Points: 9
Solved Threads: 3
 
DefaultTableModel tableModel = new javax.swing.table.DefaultTableModel();
     tabel.setModel(tableModel);
        

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


Why doesn't this work?

Buffalo101
Junior Poster
116 posts since Oct 2009
Reputation Points: 9
Solved Threads: 3
 

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

Buffalo101
Junior Poster
116 posts since Oct 2009
Reputation Points: 9
Solved Threads: 3
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: