Issue
I have a Web Service which returns ArrayList<String>
from Database. I need to populate a jTable
on client Java application with that ArrayList
. How can I organise the ArrayList
, so it shows in correct rows on the table? Currently it returns every element, separated with comma.
Here is the WebMethod bit:
@WebMethod(operationName = "ListCustomers")
public ArrayList ListCustomers() {
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/BankDB", "bankadmin", "bankadmin");
Statement st = con.createStatement();
PreparedStatement prst = con.prepareStatement("select Name, AccountNumber from CUSTOMERS");
ArrayList<String> list = new ArrayList<>();
ResultSet rs = prst.executeQuery();
while(rs.next()){
String nm = rs.getString("Name");
String an = rs.getString("AccountNumber").toString();
list.add(new String (nm));
list.add(new String (an));
}
return (ArrayList) list;
}
catch(SQLException ex){
System.err.println(ex.getMessage());
return null;
}
catch (ClassNotFoundException ex) {
Logger.getLogger(BankServerService.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("second");
return null;
}
finally{
if(st != null){
try {
st.close();
}
catch(SQLException ex){
System.out.println("Could not close statement");
}
}
}
}
This returns:
[TestName1, 46484654897, Name2, 646543543, emp3, 534354354]
The client node looks like this, which I run in another method:
listCustomers();
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
Object rowData[] = new Object[listCustomers().size()];
for (int i=0; i<listCustomers().size(); i++){
rowData[i] = listCustomers().get(i);
model.addRow(rowData);
}
This populates only TestName1, 46484654897,
into like 10 rows.
I need to show TestName1, Name2, emp3,
on separate rows on 1st column of the table, and 46484654897, 646543543, 534354354
on separate rows on 2nd column.
Solution
If your goal is to put each name/account number combination on it's own row, but you've got them all in a single list you would need to do something a bit different.
listCustomers();
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
for(int i = 0; i < listCustomers.size(); i+=2){
Object[] rowdata = new Object[] {listCustomers.get(i), listCustomers.get(i+1)};
model.addRow(rowdata);
}
You increment i by 2 each time, since you only care about name + account number combo, and it goes in pairs.
Secondly you only want to pass model.addRow the object array with the data you want for that row. You were adding every string in listcustomer to it, then adding the whole array to the model as a row.
Above I just added a new rowdata object array inside the for loop, and populated it with the value at i (the name) and the value at i+1 (the account number). Keep in mind this will get out of sync if for some reason a name or account number is missing.
Answered By - Eric B