我一直在研究一个返回数组列表的Web服务。如何将返回的数组列表添加到 jtable 并显示?
ArrayList customerDetails = new ArrayList();
try {
String sqlQuery = "SELECT * FROM customer WHERE AccountNumber="+accountNumber;
PreparedStatement stmt = DatabaseConnection.dBconn().prepareStatement(sqlQuery);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
customerDetails.add(rs.getString("Name"));
customerDetails.add(rs.getString("DoB"));
customerDetails.add(rs.getString("Address"));
customerDetails.add(rs.getString("Mobile"));
customerDetails.add(rs.getString("Email"));
customerDetails.add(rs.getString("AccountType"));
customerDetails.add(rs.getString("AccountNumber"));
customerDetails.add(rs.getString("SortCode"));
customerDetails.add(rs.getString("Balance"));
customerDetails.add(rs.getString("Card"));
}
return customerDetails;
} catch (SQLException err) {
System.out.println(err.getMessage());
}
return customerDetails;
让我们从您的ArrayList
不是结构化为行/列分组的事实开始,您将需要一个List
中的List
,其中外部列表是行,内部列表是列值
当我们使用它时,让我们也正确利用PreparedStatement
并管理资源,以便在我们使用它时正确关闭它们
ArrayList<List<String>> customerDetails = new ArrayList<>(25);
String sqlQuery = "SELECT * FROM customer WHERE AccountNumber=?";
try (PreparedStatement stmt = DatabaseConnection.dBconn().prepareStatement(sqlQuery)) {
stmt.setString(1, accountNumber);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
List<String> rowDetails = new ArrayList<>(10);
rowDetails.add(rs.getString("Name"));
rowDetails.add(rs.getString("DoB"));
rowDetails.add(rs.getString("Address"));
rowDetails.add(rs.getString("Mobile"));
rowDetails.add(rs.getString("Email"));
rowDetails.add(rs.getString("AccountType"));
rowDetails.add(rs.getString("AccountNumber"));
rowDetails.add(rs.getString("SortCode"));
rowDetails.add(rs.getString("Balance"));
rowDetails.add(rs.getString("Card"));
customerDetails.add(rowDetails);
}
}
} catch (SQLException err) {
System.out.println(err.getMessage());
}
return customerDetails;
查看使用预准备语句和试用资源语句以获取更多详细信息
现在,我们需要一个可以在非常基本的层面上支持它的TableModel
......
public class ListTableModel extends AbstractTableModel {
private List<List<String>> rows;
private List<String> columnNames;
public ListTableModel(List<String> columnNames, List<List<String>> rows) {
this.rows = new ArrayList<>(rows);
this.columnNames = columnNames;
}
@Override
public int getRowCount() {
return rows.size();
}
@Override
public int getColumnCount() {
return columnNames.size();
}
@Override
public String getColumnName(int column) {
return columnNames.get(column);
}
@Override
public Class<?> getColumnClass(int columnIndex) {
Class type = String.class;
return type;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
List<String> rowData = rows.get(rowIndex);
return rowData.get(columnIndex);
}
}
这将对列名进行List
,对行数据进行List<List>
。
就个人而言,我更愿意将数据包装到某种普通的旧Java对象(POJO)中,因为它封装了数据并在显示数据时提供了更大的灵活性(即,如果我不想,我需要显示对象的所有属性)
查看如何使用表格以获取更多详细信息