我的最终解决方案(部分感谢这位代码大师 http://www.codeguru.com/forum/archive/index.php/t-429160.html)是创建一个扩展 JTable 并覆盖的匿名内部类changeSelection()
。尝试了一个单独的类,因为我读到有些人不认为匿名内部类是好的面向对象设计,但我需要了解编辑状态,而且我必须调用保存/丢弃方法。无论如何,当它是您自己的代码时,谁需要封装? ;-)
jTableMemberList = new JTable() {
public void changeSelection(int rowIndex, int columnIndex, boolean toggle,
boolean extend) {
// Member is being edited and they've clicked on a DIFFERENT row (this
// method gets called even when the selection isn't actually changing)
if (editModeIsActive && getSelectedRow() != rowIndex) {
// User was editing, now they're trying to move away without saving
Object[] options = {"Save", "Discard", "Cancel"};
int n = JOptionPane.showOptionDialog(this,
"There are unsaved changes for the "
+ "currently selected member.\n\n"
+ "Would you like to save them?",
"Save changes?",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE,
null,
options,
options[0]);
if (n == JOptionPane.YES_OPTION) {
saveChanges();
} else if (n == JOptionPane.NO_OPTION) {
discardChanges();
} else {
// Exit without passing call on to super
return;
}
}
// make the selection change
super.changeSelection(rowIndex, columnIndex, toggle, extend);
}
};
到目前为止,这个解决方案似乎有效,但我还没有对其进行广泛的测试。这段代码的黑暗角落中可能潜伏着错误或陷阱......
希望它对其他人有帮助!