我已经更新了数据库,并且想使用与按钮单击事件绑定(bind)的代码刷新 JTable
,但它不起作用。当我关闭应用程序并再次打开它时,JTable
显示正确的数据。
我需要重写抽象表上的某些方法吗?
try {
model=new MyTableModel(this.database);
table = new JTable(model);
} catch (SQLException e) {
e.printStackTrace();
}
scrollPane = new JScrollPane(table);
refresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
((MyTableModel)table.getModel()).fireTableDataChanged();
}
});
class MyTableModel extends AbstractTableModel {
private int i;
private String[] columnNames = { "ID", "Code", "Country", "Radio",
"primljeno", "select" };
private Object[][] data = { { new Integer(0), "", "", "", "",
new Boolean(false) } };
public MyTableModel(My_class_Database database)throws SQLException {
init(database);
}
public void init(My_class_Database database) throws SQLException
{
this.i = database.checkIsDataThere();
Object[][] object;
if (i == 0) {
object = new Object[i][7];
object = database.getDatafromDatabase(this.i);
this.data = object;
dataAp = object;
} else {
object = database.getDatafromDatabase(this.i);
textField.setText("No data in database");
}
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
public String getColumnName(int col) {
return columnNames[col];
}
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
}
// problem sa null vrijednostima,null exception
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public boolean isCellEditable(int row, int col) {
if (col > 4) {
return true;
} else
return (false);
}
}
最佳答案
事实上(发布的代码),模型不知道数据库中的修改。您可以刷新模型中的数据,例如调用现有的 init() 方法或创建类似的方法。作为替代方案,您可以构建一个新模型并将其重置在 table 上。
模型负责触发通知,例如您在 actionPerformed
中使用的 fireTableDataChanged
。表客户端不应执行这些方法。例如,fireTableDataChanged
属于init()
方法。请参阅Firing Data Change Events了解更多详细信息和示例。
模型应该与数据相关,因此最好将设置 textField
的逻辑移出模型。如果需要,您可以公开模型中的其他方法,以帮助客户获取有关数据和状态的其他详细信息。
关于java - 如何让JTable在更新数据库后显示刷新的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15076301/