简体   繁体   中英

How to display column name and set scrollbar to jtable?

connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement st = connection.createStatement();
ResultSet result = st.executeQuery("select * from department");
table_1.setModel(buildTableModel(result));

method:

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);
}

result:

在此处输入图片说明

You need to wrap your JTable inside a JScrollPane , and add the resulting JScrollPane to your layout.

The sample code you provided does not show how you're adding the JTable to the JPanel or JFrame of your application.

Found a solution:

I put a JScrollPane in jframe then use following code:

connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement st = connection.createStatement();
ResultSet result = st.executeQuery("select * from department");
JTable t=new JTable();
t.setModel(buildTableModel(result));
s1.setViewportView(t);

s1 is JScrollPane.

Output:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM