1

每次我实现数据库查看器时,我都有一些填充表和调整列大小的函数。我想找到可以查看查询结果的现成组件,还可以对表中的条目进行排序、编辑并根据数据自动调整列的大小。我想使用元数据自动定义实体的类型。我将传递的唯一内容是查询的 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);
}

而且我还有一个调整列大小的类。

4

1 回答 1

0
To sort records use order by Clause to query you fire to get all records.
Use TableColumnModel to set column size.
Here is the code


//Your Edit Code
rs=st.executeQuery("select * from ManageVendor order by SName");
            table.setModel(buildTableModel(rs));
            TableColumnModel tcm=table.getColumnModel();
            tcm.getColumn(0).setPreferredWidth(50);
            tcm.getColumn(1).setPreferredWidth(200);
            tcm.getColumn(2).setPreferredWidth(150);
            tcm.getColumn(3).setPreferredWidth(60);
            tcm.getColumn(4).setPreferredWidth(50);
            tcm.getColumn(5).setPreferredWidth(250);
于 2013-12-23T06:40:54.717 回答