0
votes

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?

3
Use a custom table model, that will be the best way. - MJSG
What is a in the program? It seems as though you're trying to get an object mapped to an index greater than the length of the array, since j is supposed to be lower than the length maybe a is greater? - pimmen
It was just mistake. I meant n - Dominika
Could you give me the example of custom model? Link? I have heard about it for the first time (imma kind of beginner). - Dominika

3 Answers

1
votes

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..

0
votes

I think (I didn't checked it) that your JTable tries to add a row but it doesn't have any column because of your addColumn(null).

Why don't you just do model.addColumn(""); with an empty string to add an empty cell ?

0
votes

From what I can deduce, you want to use the variable nas an int. The getText() method will return the value as a string and the valueOf() method will return the string as a string. valueOf() is used for the exact opposite of what you want, converting an int for example into a string. You should use Integer.parseInt() instead outlined in this Stackoverflow question. That will hopefully get rid of the out of bound exceptions.