Brian Mwai
Brian Mwai

Reputation: 11

unable to get all row data from Jtable using for loop.. Giving me last row

Am trying to get row data from my Jtable using for loop but it is giving the last row. Below a sample of my code:

String item = null; String qty = null; String price = null;
for (int i = 0; i < table.getRowCount(); i++) {
    String f1 =item.getValueAt(i, 0).toString();
    String f2 =item.getValueAt(i, 1).toString();  
    String f3 =item.getValueAt(i, 2).toString(); 
    item = f1; qty = f2; price =f3;
}
Formatter fd = new Formatter();
System.out.println(fd.format("%-20s %5s %10s", item ,qty ,price ));

Upvotes: 1

Views: 46

Answers (2)

Nikolas
Nikolas

Reputation: 44486

You reassign new values to the variables item, qty and price with each loop. Hence only the last one is printed out. If you wish to print the values of each row, include the printing to console code inside the loop.

for (int i = 0; i < table.getRowCount(); i++) {
    String f1 = item.getValueAt(i, 0).toString();
    String f2 = item.getValueAt(i, 1).toString();  
    String f3 = item.getValueAt(i, 2).toString(); 
    System.out.println(String.format("%-20s %5s %10s", f1 , f2, f3));
}

Moreover, the method String.format(..) might be more interesting for you.

Upvotes: 1

O. Jones
O. Jones

Reputation: 108841

Try moving the last two lines of your sample code so they are inside your loop: before the } that ends the loop.

Upvotes: 1

Related Questions