从数据库中删除项目后刷新jtable [英] Refresh jtable after Delete An item from database
问题描述
从jtable删除项目自动刷新不起作用...
Delete an item from jtable auto refresh is not working...
这是代码
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnEdit) {
} else if (e.getSource() == btnDelete) {
String str = JOptionPane.showInputDialog(null,
"Enter The Reason : ", "", 1);
if (str != null) {
Book updatebook = new Book();
updatebook.setName(book.getName());
updatebook.setAuthor(book.getAuthor());
updatebook.setPublisher(book.getPublisher());
updatebook.setDelete(true);
ServiceFactory.getBookServiceImpl().updateBook(updatebook);
JOptionPane.showMessageDialog(null, "You entered the Reason : "+ str, "", 1);
**Refresh code**
listPanel.removeAll();
listPanel.repaint();
listPanel.revalidate();
getBooks();
getListBookPanel();
booktable.repaint();
booktable.revalidate();
} else
JOptionPane.showMessageDialog(null,
"You pressed cancel button.", "", 1);
}
}
getBooks()函数
public JTable getBooks() {
booktable = new JTable();
String[] colName = { "Name", "Author ",
"Publisher" };
List<Book> books = ServiceFactory.getBookServiceImpl().findAllBook();
data = new Object[books.size()][100000];
for (Book book : books) {
data[i][0] = book.getName();
data[i][1] = book.getAuthor();
data[i][2] = book.getPublisher();
i++;
}
DefaultTableModel dtm = new DefaultTableModel(data, colName);
booktable = new JTable();
booktable.setModel(dtm);
dtm.fireTableDataChanged();
booktable.setCellSelectionEnabled(true);
booktable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int row = booktable.getSelectedRow();
CallNo = (booktable.getValueAt(row, 0).toString());
}
});
return booktable;
}
错误
"AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException:2
"AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2
如果您知道此错误,我不知道为什么会发生此错误,请在这里分享.
i don't know why this error occured if u knew about this please share here..
推荐答案
您尝试删除数据的方式似乎效率低下,而不正确.您似乎要对代码执行的操作是创建另一个表,然后将其替换为新表.不要那样做只需更新TableModel
.您可以使用它的方法
The way you're attempting to remove data seems vary inefficient and just incorrect. It looks like what you are trying to do with your code is create a whole other table and replacing it with a new one. Don't do that. Just update the TableModel
. You can just use its method
-
public void removeRow(int row)
-从该模型.删除行的通知将发送给所有侦听器.
仅使用此方法,就会自动从表中删除一行.因此,您可以在听众的某个地方做类似的事情
Just using this method, will automatically remove a row from the table. So you can just do something like this, somewhere in a listener
DefaultTableModel model = (DefaultTableModel)bookTable.getModel();
int row = ...
model.removeRow(row);
您拥有**Refresh code**
的所有代码看起来根本没有必要.
All you code where you have **Refresh code**
looks simply unnecessary.
查看 DefualtTableModel 以获得更多方法,例如添加行等.
Look at DefualtTableModel for more methods, like adding rows and such.
这篇关于从数据库中删除项目后刷新jtable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!