我认为从的实例构建模型的最简单方法ResultSet如下。
public static void main(String[] args) throws Exception { // The Connection is obtained ResultSet rs = stmt.executeQuery("select * from product_info"); // It creates and displays the table JTable table = new JTable(buildTableModel(rs)); // Closes the Connection JOptionPane.showMessageDialog(null, new JScrollPane(table));}方法buildTableModel:public static DefaultTableModel buildTableModel(ResultSet rs) throws SQLException { ResultSetmetaData metaData = rs.getmetaData(); // names of columns Vector<String> columnNames = new Vector<String>(); int columnCount = metaData.getColumnCount(); for (int column = 1; column <= columnCount; column++) { columnNames.add(metaData.getColumnName(column)); } // data of the table Vector<Vector<Object>> data = new Vector<Vector<Object>>(); while (rs.next()) { Vector<Object> vector = new Vector<Object>(); for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) { vector.add(rs.getObject(columnIndex)); } data.add(vector); } return new DefaultTableModel(data, columnNames);}更新
你喜欢用
javax.swing.SwingWorker吗?你喜欢使用该
try-with-resources语句吗?
public class GUI extends Jframe { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { new GUI().setVisible(true); } }); } private final JButton button; private final JTable table; private final DefaultTableModel tableModel = new DefaultTableModel(); public GUI() throws HeadlessException { setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); table = new JTable(tableModel); add(new JScrollPane(table), BorderLayout.CENTER); button = new JButton("Load Data"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { loadData(); return null; } }.execute(); } }); add(button, BorderLayout.PAGE_START); setSize(640, 480); } private void loadData() { LOG.info("START loadData method"); button.setEnabled(false); try (Connection conn = DriverManager.getConnection(url, usr, pwd); Statement stmt = conn.createStatement()) { ResultSet rs = stmt.executeQuery("select * from customer"); ResultSetmetaData metaData = rs.getmetaData(); // Names of columns Vector<String> columnNames = new Vector<String>(); int columnCount = metaData.getColumnCount(); for (int i = 1; i <= columnCount; i++) { columnNames.add(metaData.getColumnName(i)); } // Data of the table Vector<Vector<Object>> data = new Vector<Vector<Object>>(); while (rs.next()) { Vector<Object> vector = new Vector<Object>(); for (int i = 1; i <= columnCount; i++) { vector.add(rs.getObject(i)); } data.add(vector); } tableModel.setDataVector(data, columnNames); } catch (Exception e) { LOG.log(Level.SEVERE, "Exception in Load Data", e); } button.setEnabled(true); LOG.info("END loadData method"); }}


