用JTable顯示資料庫資料
阿新 • • 發佈:2019-01-29
用到DefaultTabelModel類
public class JTableTest { public static void main(String[] args) throws DAOException { DefaultTableModel model = new DefaultTableModel(0,3); JTable table = new JTable(model); JFrame jf = new JFrame(); ICostDAO dao = DAOFactory.getCostDAO(); model.setRowCount(0); try { List<Cost> costs = dao.findAll(); for(int i=0;i<costs.size();i++){ Cost c = (Cost)costs.get(i); Object[] obj = {c.getId(), c.getCostType(), c.getName()}; model.insertRow(table.getSelectedRowCount(), obj); } jf.add(table); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setSize(500, 300); jf.setLocationRelativeTo(null); jf.setVisible(true); } catch (DAOException e) { e.printStackTrace(); throw new DAOException("查詢資料失敗",e); } finally{ DBUtil.close(); } } }