我在方法中创建了一个OrderModel
对象,用于从DB获取值并将其设置为JTable
。我想知道如何使用以下代码将此创建的对象设置为JTable
:
tblOrderItems.setModel(DbUtils.resultSetToTableModel());
这是我的代码:
private void tblOrderListMouseClicked(java.awt.event.MouseEvent evt) {
int raw = tblOrderList.getSelectedRow();
OrderModel or;
String item;
Double qty,amount,total;
ArrayList<OrderModel> arrOrder = new ArrayList<OrderModel>();
String selectedRaw = tblOrderList.getModel().getValueAt(raw, 0).toString();
String sql = "select item,qty,amount from orderdetails where orderid='"+selectedRaw+"'";
con = new DBconnector().connect();
try {
ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if(rs.next()){
or = new OrderModel();
or.setItem(rs.getString("item"));
or.setQty(rs.getDouble("qty"));
or.setAmount(rs.getDouble("amount"));
arrOrder.add(or);
DefaultTableModel tblModel = new DefaultTableModel();
// wanted to set ArrayList to table+
tblOrderItems.setModel(DbUtils.resultSetToTableModel());
}
} catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:3)
首先创建一个自己的zip -d file.jar 'META-INF/*.SF' 'META-INF/*.RSA'
,它可以管理您的TableModel
类,它代表表格中的一行......
OrderModel
然后你就可以使用......
public static class OrderTableModel extends AbstractTableModel {
protected static final String[] COLUMN_NAMES = {"Item", "Qty", "Amount"};
private List<OrderModel> rows;
public OrderTableModel(List<OrderModel> rows) {
this.rows = new ArrayList<>(rows);
}
@Override
public int getRowCount() {
return rows.size();
}
@Override
public int getColumnCount() {
return COLUMN_NAMES.length;
}
@Override
public String getColumnName(int column) {
return COLUMN_NAMES[column];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object value = null;
OrderModel row = rows.get(rowIndex);
switch (columnIndex) {
case 0:
value = row.getItem();
break;
case 1:
value = row.getQty();
break;
case 2:
value = row.getAmount();
break;
}
return value;
}
}
只需加载private void tblOrderListMouseClicked(java.awt.event.MouseEvent evt) {
int raw = tblOrderList.getSelectedRow();
OrderModel or;
String item;
Double qty, amount, total;
ArrayList<OrderModel> arrOrder = new ArrayList<OrderModel>();
String selectedRaw = tblOrderList.getModel().getValueAt(raw, 0).toString();
String sql = "select item,qty,amount from orderdetails where orderid=?";
con = new DBconnector().connect();
try (PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, selectedRaw);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
or = new OrderModel();
or.setItem(rs.getString("item"));
or.setQty(rs.getDouble("qty"));
or.setAmount(rs.getDouble("amount"));
arrOrder.add(or);
}
OrderTableModel model = new OrderTableModel(arrOrder);
tblOrderItems.setModel(model);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
中的项目,然后将其传递到ArrayList
的实例,然后应用于OrderTableModel
有关使用自定义模型的详细信息,请查看How to Use Tables。
有关如何使用JTable
的详细信息,请查看Using Prepared Statements
有关如何更好地管理数据库(和其他)资源的更多详细信息,请查看The try-with-resources Statement