Explisam
Explisam

Reputation: 749

Inserting a dynamic 2D array into a tableview

Basically i have got four 2D matrices below which i want to insert each into a separate tableview. The range is dynamic and columns should be serialized as {1, 2, 3 ..etc}

I'm trying to create a function for the insertion but i could not find a way to do it other than defining a fixed length and only use the required range.

int rowLen, colLen = textfield_input;

double[][] Ci = new double[rowLen][colLen];
double[][] ThetaP = new double[rowLen][colLen];
double[][] ThetaT= new double[rowLen][colLen];
double[][] Re = new double[rowLen][colLen];

void printMatrix(TableView target, double[][] source) {

}

Upvotes: 0

Views: 972

Answers (1)

James_D
James_D

Reputation: 209225

Make your table a TableView<double[]> (so each row is represented by a double[]), and create table columns according to the size of the rows.

If you can assume your array is rectangular (i.e. source[i].length is the same for all i), you can do:

void printMatrix(TableView<double[]> target, double[][] source) {

    target.getColumns().clear();
    target.getItems().clear();

    int numRows = source.length ;
    if (numRows == 0) return ;

    int numCols = source[0].length ;

    for (int i = 0 ; i < numCols ; i++) {
        TableColumn<double[], Number> column = new TableColumn<>("Column "+i);
        final int columnIndex = i ;
        column.setCellValueFactory(cellData -> {
            double[] row = cellData.getValue();
            return new SimpleDoubleProperty(row[columnIndex]);
        });
        target.getColumns().add(column);
    }

    for (int i = 0 ; i < numRows ; i++) {
        target.getItems().add(source[i]);
    }
}

If the array might not be rectangular, you can add additional columns as you go. You need to be careful to ensure that you don't index out of any of the arrays that make up the rows:

void printMatrix(TableView<double[]> target, double[][] source) {

    target.getColumns().clear();
    target.getItems().clear();

    int numRows = source.length ;

    for (int rowIndex = 0 ; rowIndex < numRows ; rowIndex++) {
        for (int i = target.getColumns().size(); i < source[rowIndex].length ; i++) {
            TableColumn<double[], Number> column = new TableColumn<>("Column "+i);
            final int columnIndex = i ;
            column.setCellValueFactory(cellData -> {
                double[] row = cellData.getValue();
                double value ;
                if (row.length <= columnIndex) {
                    value = 0 ;
                } else {
                    value = row[columnIndex] ;
                }
                return new SimpleDoubleProperty(value);
            });
            target.getColumns().add(column);
        }
        target.getItems().add(source[rowIndex]);
    }
}

Upvotes: 1

Related Questions