数据库可JTable交互

时间:2013-07-18 08:21:39

标签: java database swing jtable

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

我还有一个可以调整列大小的类。

1 个答案:

答案 0 :(得分: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);