javajtablejform

add row and column to jTable in one loop


I am working in NetBeans IDE, language Java, the main class is JFrameForm.

I have a jTable tab with just one row and one column, button and jTextField en, where type should be integers. The input is variable n.

I need to create matrix with n rows and n columns. So n x n dimension of matrix as a jTable.

After click on the button, variable n will be saved as dimension and loop will start add the column and row till n.

The code is following:

private void sendMouseClicked(java.awt.event.MouseEvent evt) {                                    
        DefaultTableModel model = (DefaultTableModel) tab.getModel();

        String sn=en.getText();
        int n=Integer.valueOf(sn);

        for(int j=2;j<=n;j++){
            model.addColumn(null); // I know this is wrong
            model.addRow(new Object[]{test.getText()+j});
            test.setText(test.getText()+j);
        }
    }         

I got error

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1

The cells should be empty.

Please help me to input the column. What is object there?


Solution

  • set column names to JTable and then add rows in JTable..

    private void sendMouseClicked(java.awt.event.MouseEvent evt) {                                    
        String sn=en.getText();
        int n=Integer.valueOf(sn);
        java.util.Vector columns = new java.util.Vector();
        columns.add("Your Column Name");
        java.util.Vector rows = new java.util.Vector();
        for(int j=2;j<=n;j++){
            java.util.Vector row = new java.util.Vector();
            row.add(test.getText()+j);
            rows.add(row);
            test.setText(test.getText()+j);
        }
        DefaultTableModel model = new DefaultTableModel(rows, columns);
        tab.setModel(model);
    }
    

    this will work..