Reputation: 111
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.
Upvotes: 3
Views: 1961
Reputation: 1424
int c = evt.getClickCount();
if (c == 2) {
int res = JOptionPane.showConfirmDialog(null, "Are you sure to delete this data?", "", JOptionPane.YES_NO_OPTION);
switch (res) {
case JOptionPane.YES_OPTION:
int p = table.getSelectedRow();
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.removeRow(p);
JOptionPane.showMessageDialog(null, "Delete Successfully");
break;
case JOptionPane.NO_OPTION:
JOptionPane.showMessageDialog(null, "Delete Action is Canceled");
break;
}
}
Upvotes: 1
Reputation: 324118
myTableModel extends from AbstractTableModel.
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:
DefaultTableModel model = (DefaultTableModel)table.getModel();
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.
Upvotes: 2