java刷新JTable?
有人能解释为什么会发生这种情况(见下图)以及如何解决它吗
public class DataVector
{
Connection connect = null;
Statement statement = null;
DefaultTableModel tableModel = new DefaultTableModel();
public DataVector() {}
public void GetData (JTable table)
{
String []colsName = {"MÃ NHÂN VIÊN", "HỌ NHÂN VIÊN", "TÊN NHÂN VIÊN", "GIỚI TÍNH", "NĂM SINH", "TRÌNH ĐỘ", "SỐ ĐT", "ĐỊA CHỈ"};
tableModel.setColumnIdentifiers(colsName); // đặt tiêu đề cột cho tableModel
connectSQL();
updateData(view());// gọi hàm view để truy suất dữ liệu sau đó truyền cho hàm updateData để đưa dữ liệu vào tableModel và hiện lên Jtable trong Frame
table.setModel(tableModel);
}
public void updateData(ResultSet result)
{
String []colsName = {"MÃ NHÂN VIÊN", "HỌ NHÂN VIÊN", "TÊN NHÂN VIÊN", "GIỚI TÍNH", "NĂM SINH", "TRÌNH ĐỘ", "SỐ ĐT", "ĐỊA CHỈ"};
tableModel.setColumnIdentifiers(colsName); // Đặt tiêu đề cho bảng theo các giá trị của mảng colsName
try {
while(result.next())
{ // nếu còn đọc tiếp được một dòng dữ liệu
String rows[] = new String[8];
rows[0] = result.getString(1); // lấy dữ liệu tại cột số 1 (ứng với mã hàng)
rows[1] = result.getString(2);
rows[2] = result.getString(3);
rows[3] = result.getString(4);
rows[4] = result.getString(5);
rows[5] = result.getString(6);
rows[6] = result.getString(7);// lấy dữ liệu tai cột số 2 ứng với tên hàng
rows[7] = result.getString(8);
tableModel.addRow(rows); // đưa dòng dữ liệu vào tableModel để hiện thị lên jtable
//mỗi lần có sự thay đổi dữ liệu ở tableModel thì Jtable sẽ tự động update lại trên frame
}
} catch (SQLException e) {}
}
public void connectSQL(){
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbc? useUnicode=true&characterEncoding=UTF-8";
try {
connect = DriverManager.getConnection(url,"root","");
System.out.println("Kết nối thành công");
} catch (SQLException e) {}
} catch (ClassNotFoundException e) {}
}
public ResultSet view(){
ResultSet result = null;
String sql = "SELECT * FROM nhanvien";
try {
Statement statement = (Statement) connect.createStatement();
return statement.executeQuery(sql);
} catch (SQLException e) {}
return result;
}
}
这是我向JTable显示数据库的代码
public void Add () throws SQLException
{
String sql;
String mNV = STF.TX1.getText();
String hNV = STF.TX2.getText();
String tNV = STF.TX3.getText();
String gT = SB.TX4.getText();
String nS = STF.TX5.getText();
String tD = STF.TX6.getText();
String sDT = STF.TX7.getText();
String dC = STF.TX8.getText();
sql = "INSERT INTO `nhanvien` "
+ "(`MÃ NV`, `HỌ NV`, `TÊN NV`, `GIỚI TÍNH`, `NĂM SINH`, `TRÌNH ĐỘ`, `SỐ ĐT`, `ĐỊA CHỈ`) "
+ "VALUES ('"+mNV+"', '"+hNV+"', '"+tNV+"', '"+gT+"', '"+nS+"', '"+tD+"', '"+sDT+"', '"+dC+"');";
AD.Add(sql);
}
这是添加按钮。 在添加之前
在添加之后
共 (0) 个答案