Mat*_*att 5 java user-interface swing jtable selection
我发现这个论坛帖子建议覆盖 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
是否可以在 ListSelectionModel 更改的中间插入阻塞代码?有没有更好的方法来拦截选择更改事件?
我已经在倾听他们的声音,但那时已经发生了变化。
我的最终解决方案(部分感谢这位代码大师)是创建一个扩展 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);
}
};
Run Code Online (Sandbox Code Playgroud)
到目前为止,这个解决方案似乎有效,但我还没有对其进行广泛的测试。这段代码的黑暗角落中可能潜伏着错误或陷阱......
希望它对其他人有帮助!
| 归档时间: |
|
| 查看次数: |
3124 次 |
| 最近记录: |