如果
ResultSet.getObject(index)用于填充表格,这应该可以工作。JDBC驱动程序将根据JDBC规范中定义的标准映射返回适当的对象类型(例如,int列将映射到
java.lang.Integer,等等)。
我不特别喜欢您链接的代码:它会产生很多有关类型安全的警告,您应该注意这些警告。我会用这样的东西(caveat:未测试):
数据包装器类:
public class DataResult { private final List<String> columnNames ; private final List<List<Object>> data ; public DataResult(List<String> columnNames, List<List<Object>> data) { this.columnNames = columnNames ; this.data = data ; } public int getNumColumns() { return columnNames.size(); } public String getColumnName(int index) { return columnNames.get(index); } public int getNumRows() { return data.size(); } public Object getData(int column, int row) { return data.get(row).get(column); } public List<List<Object>> getData() { return data ; }}数据库访问器类:
public class DAO { private Connection conn ; public DAO() { // initialize connection... } public DataResult getAllData() throws SQLException { List<List<Object>> data = new ArrayList<>(); List<String> columnNames = new ArrayList<>(); try ( Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select * from some_table")) { int columnCount = rs.getmetaData().getColumnCount(); for (int i = 1 ; i <= columnCount ; i++) { columnNames.add(rs.getmetaData().getColumnName(i)); } while (rs.next()) { List<Object> row = new ArrayList<>(); for (int i = 1 ; i <= columnCount ; i++) { row.add(rs.getObject(i)); } data.add(row); } } return new DataResult(columnNames, data); }}GUI代码:
TableView<List<Object>> table = new TableView<>();DAO dao = new DAO();DataResult data = dao.getAllData();for (int i = 0 ; i < data.getNumColumns() ; i++) { TableColumn<List<Object>, Object> column = new TableColumn<>(data.getColumnName(i)); int columnIndex = i ; column.setCellValueFactory(cellData -> new SimpleObjectProperty<>(cellData.getValue().get(columnIndex))); table.getColumns().add(column);}table.getItems().setAll(data.getData());使用此版本,提供给表的数据包含适用于列的适当类型的对象-
不一定是字符串。因此,例如,如果数据库列使用(SQL)类型int定义,则表视图列将包含
java.lang.Integer实例,并且排序将根据的实现
Integer.compareTo(...)(即,以正确的数字顺序)。



