0

Here I want to allocate number of rows in a table dynamically using constructor. datamodel is the class and datamodel(int count) method assigns no.of row.

import javax.swing.table.AbstractTableModel;

@SuppressWarnings("serial")
public class datamodel extends AbstractTableModel{
    int row1;
    datamodel(int count){

        row1 = count;
        count = 0;
    }

    private String[] columnNames = {"Sl No","Material Code", "Material Name", "Select", "Received QTY", "Unit", "To Be Delivered", "PO No", "PO Sl"};//new String[9];
    //table has 100 rows and 9 columns
    private Object[][] data = new Object[row1][9]; 


    public int getColumnCount() { return columnNames.length; }
    public int getRowCount() { return data.length;}
    public String getColumnName(int col) {
        // TODO Auto-generated method stub
        return columnNames[col];
    }

    public Object getValueAt(int row, int col) {
        // TODO Auto-generated method stub
        return data[row][col];
    }

    @Override
    public void setValueAt(Object aValue, int row, int col) {
        // TODO Auto-generated method stub
        data[row][col] = aValue;
        fireTableCellUpdated(row, col);
    }

    public boolean isCellEditable(int rowIndex, int columnIndex) {
        // TODO Auto-generated method stub
        return true;
    }

    public Class getColumnClass(int col) {
        if((col == 4) || (col == 6))
            return Double.class;
            //return getValueAt(0, c).getClass();
        else if(col == 3)
            return Boolean.class;
        else
            return String.class;
    }
}

this is an abstracttablemodel where I want to pass the number of rows to the datamodel.

evandongen
  • 1,995
  • 17
  • 19
Praful
  • 43
  • 2
  • 6

1 Answers1

5
int row1;
datamodel(int count){   
    row1 = count;
    count = 0;
}

You're setting the local variable count to zero. That has no effect on the field row1.


Now, after having a closer look at your code. Strong advice: indent your code, stick to naming conventions an collect all field declarations at the top of the file. Then it's easier for us to understand the code..

int row1;
private Object[][] data = new Object[row1][9];

datamodel(int count) {
    row1 = count;
    count = 0;
}

What you want to do: pass the value with the constructor so that the array gets initialized. Your approach won't work, because the array is created before the constructor method get's executed. So you always have a Object[0][9], regardless what you pass with the constructor.

You should create the array inside the constructor method instead:

int row1;
private Object[][] data;

datamodel(int count) {
    row1 = count;
    data = new Object[count][9];
}
Andreas Dolk
  • 113,398
  • 19
  • 180
  • 268