将数据插入数据库后如何刷新JTable? [英] How to refresh JTable after inserting data to database?
问题描述
我正在从Access数据库填充JTable.首次运行代码时,表可以完美加载.然后从JDialog将新记录添加到数据库.我试图做的是在JDialog关闭但表未更新时调用loadData()
方法.
I'm populating JTable from access database. when running the code for the first time, table loads perfectly. Then adding new records to database from JDialog. What I was trying to do is to call loadData()
method when JDialog is closed, but table is not updating.
这是我的loadData()
方法:
private void loadData() {
System.out.println("sssss");
final String [] columnNames={"Seq", "First Name", "Last Name","Num1","Num2","Num3"};
connectDb();
data = new Object[rows][columns];
int row = 0;
try {
while(rs.next()){
for(int col = 0 ; col<columns; col++ ){
if(col==0)
data[row][col]=rs.getString("contact_seq");
if(col==1)
data[row][col]=rs.getString("contact_fname");
if(col==2)
data[row][col]=rs.getString("contact_lname");
if(col==3)
data[row][col]=rs.getString("contact_num1");
if(col==4)
data[row][col]=rs.getString("contact_num2");
if(col==5)
data[row][col]=rs.getString("contact_num3");
}
row++;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
model = new DefaultTableModel(data, columnNames){
/**
*
*/
private static final long serialVersionUID = 1L;
public boolean isCellEditable(int row, int column)
{
return false;
}
};
table = new JTable(model);
}`
这是我在关闭JDialog时如何调用loadData方法的方法.
this how I call loadData method when closing the JDialog.
JMenuItem mntmNew = new JMenuItem("New Contact");
mntmNew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addData gui = new addData(viewData.this,rs);
gui.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
gui.setVisible(true);
gui.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e){
loadData();
}
});
}
});
mnFile.add(mntmNew);
添加记录时,我的数据库已更新,但Jtable未刷新.
My database is updated when adding the records but Jtable is not refreshed.
推荐答案
此处:
private void loadData() {
...
table = new JTable(model); // don't re-create the table here
}
不要重新创建表,而是通过设置新表模型或清除并重新填充当前表模型来更新其模型:
Don't re-create the table but update its model instead, either by setting a new table model or by clearing and re-filling the current one:
private void loadData() {
...
table.setModel(model);
// Of course, table should have been initialized
// and placed first, and only once!
}
请参见示例此处(包括在后台线程中进行数据库调用的SwingWorker),此处.请查看这些答案,其中有一些解释可以使您清楚地说明这一点.
See examples here (includes SwingWorker to make database calls in a background thread), here and here. Please have a look to those answers, there are explanations to make the point clear.
这篇关于将数据插入数据库后如何刷新JTable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!