NULL Pointer
NULL Pointer

Reputation: 129

How to fill 2 d array dynamically

I want to display resultset value with this pattern:

Object rowData[][] = { { url , tags , text }, { url , tags , text } };

My code is:

while (res.next()) {
    String url = res.getString(1);
    String tags = res.getString(2);
    String text = res.getString(3);
}
Object rowData[][] = { { "Row1-Column1", "Row1-Column2", "Row1-Column3" },
                { "Row2-Column1", "Row2-Column2", "Row2-Column3" } };

Object columnNames[] = { "URL", "Tag Information", "Text" };
JTable table = new JTable(rowData, columnNames);`

Upvotes: 1

Views: 64

Answers (3)

Sandip Patel
Sandip Patel

Reputation: 33

Below is conde snippet which can be used to achieve what you want.

int rowcount = 0;
if (res.last()) {
    rowcount = res.getRow();
    res.beforeFirst();
}
Object rowData[][] = new Object[rowcount][];
int count = 0;
while (res.next()) {
    rowData[count] = new Object[]    {res.getString(1),res.getString(1),res.getString(3)};  
    count++;
}
Object columnNames[] = { "URL", "Tag Information", "Text" };
JTable table = new JTable(rowData, columnNames);

Upvotes: 0

jfcorugedo
jfcorugedo

Reputation: 10051

Use a List to store each file of the data, then convert the list into an Array:

List<Object[]> data = new ArrayList<Object[]>();
while (res.next()) {
    data.add(new Object[]{res.getString(1), res.getString(2),res.getString(3)});
}

Object[][] rowData = data.toArray(new Object[0][0]);
JTable table = new JTable(rowData, columnNames);

Upvotes: 1

devops
devops

Reputation: 9179

Look at this simple example:

public static void main(String[] args) {

    int rows    = 3; //res.getCount() ?
    int columns = 3;

    Object[][] rawData = new Object[rows][columns];

    for(int row = 0; row < rows; row++){
        rawData[row][0] = row + " - url";
        rawData[row][1] = row + " - tags";
        rawData[row][2] = row + " - text";
    }

    System.out.println(Arrays.toString(rawData[0])); // print first row
}

string concatenation inside of loop is a very bad idea, but this should be just an example

Upvotes: 0

Related Questions