我写的代码在将数据库中的数据读到JTable上时结果很奇怪,各位帮我看看该怎么改!
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.*;
import java.awt.*;
import java.sql.*;
import javax.swing.table.*;
import java.util.Vector;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2006</p>
*
* <p>Company: </p>
*
* @author not attributable
* @version 1.0
*/
public class Frame1 extends JFrame {
JPanel contentPane;
BorderLayout borderLayout1 = new BorderLayout();
// Object[][] cell;
// String[] columnName;
DefaultTableModel dtm = new DefaultTableModel();
Vector title = new Vector();
Vector data = new Vector();
JTable jTable1 = new JTable(GetDefaultTable());
JScrollPane jsp = new JScrollPane(jTable1);
public Frame1() {
try {
setDefaultCloseOperation(EXIT_ON_CLOSE);
jbInit();
} catch (Exception exception) {
exception.printStackTrace();
}
}
/**
* Component initialization.
*
* @throws java.lang.Exception
*/
private void jbInit() throws Exception {
contentPane = (JPanel) getContentPane();
contentPane.setLayout(borderLayout1);
setSize(new Dimension(400, 300));
setTitle("Frame Title");
contentPane.add(jsp, java.awt.BorderLayout.CENTER);
}
private javax.swing.table.DefaultTableModel GetDefaultTable() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException ce) {
JOptionPane.showMessageDialog(null, ce.toString());
}
try {
Connection con = DriverManager.getConnection("jdbc:odbc:Northwind");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from EmployeeTerritories");
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
title.add(rsmd.getColumnLabel(i)); //获得表头
dtm.addColumn(title.get(i - 1)); //添加表头
}
while (rs.next()) {
for (int j = 1; j <= rsmd.getColumnCount(); j++) {
data.addElement(rs.getString(j)); //获得列值
int k = data.size() / rsmd.getColumnCount(); //得到行数
dtm.setRowCount(k); //设置行数
dtm.addColumn(rsmd.getColumnName(j), data.toArray()); //填充列值
}
}
rs.close();
st.close();
con.close();
} catch (SQLException se) {
JOptionPane.showMessageDialog(null, se.toString());
}
return dtm;
}
}