我发现this forum thread建议覆盖ListSelectionModel以防止选择行。
我希望在当前所选项目未保存的更改(表格外部)时防止选择更改,直到用户确认丢弃。类似的东西:
public class confirmSelectionChange extends DefaultListSelectionModel {
public void setSelectionInterval(int index0, int index1) {
if (unsavedChanges()) {
super.setSelectionInterval(int index0, int index1);
}
}
private boolean unsavedChanges() {
if (noUnsavedChangesExist) {
return true;
}
// Present modal dialog: save, discard cancel
if (dialogAnswer == SAVE) {
// save changes
return true;
} else if (dialogAnswer == DISCARD) {
return true;
} else {
return false;
}
}
}
是否可以在ListSelectionModel更改中插入阻止代码?是否有更好的方法来拦截选择变更事件?
我已经在听他们了,但到那时候已经发生了变化。
答案 0 :(得分:2)
我的最终解决方案(部分归功于this code guru)是创建一个扩展JTable并覆盖changeSelection()
的匿名内部类。我读了一个单独的课,因为我读到有些人不认为匿名内部类是好的OO设计,但我需要知道编辑状态加上我必须调用save / discard方法。无论如何,谁需要封装才是你自己的代码? ; - )
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);
}
};
这个解决方案到目前为止似乎有效,但我还没有对它进行过广泛的测试。在这段代码的一个黑暗角落里可能存在漏洞或陷阱......
希望它可以帮助别人!