我有 3 节课
从数据库获取数据的冷杉
普通作品第二名
其他用于展示表。
public class TableContent {
private final Vector<String> headers;
private final Vector<Vector<String>> content;
public TableContent(final Vector<String> headers, final Vector<Vector<String>> content) {
this.headers = headers;
this.content = content;
}
public Vector<String> headers() {
return headers;
}
public Vector<Vector<String>> content() {
return content;
}
}
和:
public class TableData {
public TableContent getData() {
Vector<String> headers = new Vector<String>();
Vector<Vector<String>> content = new Vector<Vector<String>>();
try {
Connection conn = DriverManager.getConnection("");
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("Select * from table");
headers = buildHeaders(rs);
content = buildContent(rs);
} catch (SQLException e) {
e.printStackTrace();
}
return new TableContent(headers, content);
}
private Vector<String> buildHeaders(final ResultSet rs) throws SQLException {
Vector<String> headers = new Vector<String>();
int col = rs.getMetaData().getColumnCount();
for (int i = 1; i <= col; i++) {
headers.add(rs.getMetaData().getColumnName(i));
}
return headers;
}
private Vector<Vector<String>> buildContent(final ResultSet rs) throws SQLException {
Vector<Vector<String>> content = new Vector<Vector<String>>();
while (rs.next()) {
int col = rs.getMetaData().getColumnCount();
Vector<String> newRow = new Vector<String>(col);
for (int i = 1; i <= col; i++) {
newRow.add(rs.getString(i));
}
content.add(newRow);
}
return content;
}
}
和:
public class TableGUI extends JFrame {
JTable table;
TableContent data = new TableData().getData();
public TableGUI() {
table = new JTable(new DefaultTableModel(data.headers(), data.content()));
add(new JScrollPane(table), BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(700, 550);
setLocation(300, 80);
setVisible(true);
}
public static void main(String[] args) {
new TableGUI();
}
}
输出:
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Vector
at javax.swing.table.DefaultTableModel.justifyRows(DefaultTableModel.java:268)
at javax.swing.table.DefaultTableModel.setDataVector(DefaultTableModel.java:224)
at javax.swing.table.DefaultTableModel.<init>(DefaultTableModel.java:159)
at TableGUI.<init>(TableGUI.java:11)
at TableGUI.main(TableGUI.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
我的错误在哪里?