如何通过双击删除行?
我是java新手,所以我的知识非常有限。如果我忽略了一些相当明显的解决方案,我现在已经想原谅了。
我在尝试在程序中创建一个函数时遇到问题,以便用户可以通过双击一行来删除该行(从 JTable
中)。我尝试使用此代码:
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
JTable target = (JTable)e.getSource();
int deletedRow = target.getSelectedRow();
myTableModel.removeRow(deletedRow);
myTableModel.fireTableDataChanged();
}
}
myTableModel
扩展自AbstractTableModel
。我希望你们中的一些人能够帮助我。
I'm new to java, so my knowledge is quite limited. I already want to excuse now, if I have overlooked some rather obvious solution.
I'm having a problem trying to make a function in my program, so that the user can delete a row (from a JTable
) by double-clicking on it. I've tried to use this code:
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
JTable target = (JTable)e.getSource();
int deletedRow = target.getSelectedRow();
myTableModel.removeRow(deletedRow);
myTableModel.fireTableDataChanged();
}
}
myTableModel
extends from AbstractTableModel
. I hope some of you are able to help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道这意味着什么。我认为这意味着您正在使用 DefaultTableModel,因为它实现了 removeRow(...) 方法。
无需调用 fireTableDateChanged() 方法。 DefaultTableModel 的removeRow() 方法将为您完成此操作。调用这些方法是 TableModel 的责任,而不是您的自定义代码。
你的方法正在执行吗?默认情况下,双击会调用您双击的单元格的编辑器。因此,您需要重写表的 isCellEditable(...) 方法以返回 false。然后,将在表上双击,并且应调用您的侦听器代码。
此外,在您的事件代码中,您可以访问该表,因此您应该从表中获取模型,以确保您访问正确的模型:
如果您需要更多帮助(以及将来当您发布问题时),请发布您的 SSCCE 因为我们无法根据几行代码猜测您在做什么。
I don't know what that means. I assume it means you are using the DefaultTableModel, because that implements the removeRow(...) method.
There is no need to invoke the fireTableDateChanged() method. The removeRow() method of the DefaultTableModel will do that for you. It is the responsibility of the TableModel to invoke these methods, not your custom code.
Is you method being executed? By default a double click with invoke the editor of the cell you double clicked on. So you need to override the isCellEditable(...) method of your table to return false. Then a double click will be invoked on the table and your listener code should be invoked.
Also in your event code you access the table, so you should get the model from the table to make sure you are accessing the proper model:
If you need more help (and in the future when you post a question) then post your SSCCE because we can't guess what you are doing based on a couple of lines of code.