Pergunta

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:

enter image description here

Foi útil?

Solução 2

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:

enter image description here

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top