每次我实现数据库查看器时,我都有一些填充表和调整列大小的函数。我想找到可以查看查询结果的现成组件,还可以对表中的条目进行排序、编辑并根据数据自动调整列的大小。我想使用元数据自动定义实体的类型。我将传递的唯一内容是查询的 ResultSet,其余部分由组件完成。任何想法?
到目前为止我做了什么:
private 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);
}
public static void showResult(ResultSet rs) throws SQLException{
//creates the table
JTable table = new JTable(buildTableModel(rs));
table.setEnabled(false);
//abjust table size
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumnAdjuster tca = new TableColumnAdjuster(table);//the class for adjusting the column size
tca.adjustColumns();
//JFrame
JFrame view = new JFrame("View");
view.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//add to frame
JScrollPane pane = new JScrollPane(table);
view.add(pane);
//settings
view.setVisible(true);
view.setSize(table.getWidth(), 400);
}
而且我还有一个调整列大小的类。