1
我使用DefaultTableModel
爲我的JTable
模型,但不顯示我的表!簡單JTable與DefaultTableModel
public class RecordTableGUI2 extends JFrame {
JTable table;
RecordTableModel2 model2;
public RecordTableGUI2() {
model2 = new RecordTableModel2();
table = new JTable(model2);
add(new JScrollPane(table), BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new RecordTableGUI2();
}
});
}
}
模型類:
public class RecordTableModel2 extends DefaultTableModel {
Connection con;
Statement statement;
ResultSet result;
String dbUrl = "jdbc:mysql://localhost/mydb";
String query = "Select * from mytable";
Vector data = new Vector();
Vector column = new Vector();
public RecordTableModel2() {
try {
con = DriverManager.getConnection(dbUrl, "root", "2323");
statement = con.createStatement();
result = statement.executeQuery(query);
int c = result.getMetaData().getColumnCount();
for (int i = 1; i <= c; i++) {
column.add(result.getMetaData().getColumnName(i));
System.out.println(result.getMetaData().getColumnName(i)); //prints correct
}
while (result.next()) {
Vector eachRow = new Vector(c);
for (int i = 1; i <= c; i++) {
eachRow.add(result.getString(i));
System.out.println(result.getString(i)); //prints correct
}
data.add(eachRow);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
} finally {
try {
if (con != null) {
con.close();
}
if (statement != null) {
statement.close();
}
} catch (SQLException sqlee) {
sqlee.printStackTrace();
}
}
}
}
如何引入向量DefaultTableModel
?
輸出只顯示一個空白的JFrame
這是越來越討厭。 2周前,我給你提供了關於如何將數據從數據庫加載到DefaultTableModel的代碼。爲什麼你很難聽到這個建議?你到底在哪裏添加數據和列名到DefaultTableModel? DefaultTableModel不知道你的數據/列向量。再看看我給你的代碼。從工作代碼開始,然後進行更改,如果它沒有做到你想要的! – camickr
@camickr是的,我不知道如何將我的向量引入'DefaultTableModel'? – Sajad
Edxactly,你創建的向量,然後你使用向量創建DefaultTableModel。我向你展示瞭如何在其他文章中創建矢量。然後使用該模型創建JTable。 – camickr