在选择之前验证JList出现
当前,我有一个JList监听列表选择监听器。在选择之前验证JList出现
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {
// When the user release the mouse button and completes the selection,
// getValueIsAdjusting() becomes false
if (evt.getValueIsAdjusting()) {
/*
In certain situation, I may want to prevent user from selecting other
than current selection. How can I do so?
*/
}
}
在某些情况下,我可能想阻止用户选择除当前选择以外的选项。我该怎么做?
当我收到ListSelectionEvent时,似乎太晚了。但是,如果我想在ListSelectionEvent发生之前这样做,我不知道该用户正在尝试选择其他。
这里是塞纳里奥之一。
JList包含项目名称列表。 因此,每当用户选择新的列表项目时,我们需要从当前项目中打开视图,并显示新项目。 但是,当前的项目可能尚未储存。 因此,如果当前项目尚未保存,我们会要求用户确认“保存项目?” (是,否,取消) 当用户选择取消时,这意味着他想取消他的“选择到另一个项目”动作。他想坚持当前的JList选择。 我们将弹出jList1ValueChanged事件句柄中的确认对话框。 但是,当我们试图坚持当前的JList选择时,已经太晚了。
我已经为相同的工作流程用例实施了如下操作。虽然它对我来说足够有效,但我确实希望有一种更简单和更优雅的方法,在选择活动可能会在继续之前被否决。如果我有时间进行调查并找出结果,我会重新发布,但它可能会成为投资回报不值得(即定制Swing类,直接处理较低级别的鼠标/键盘事件等)的情况。无论如何,我现在正在做的是保存最后一次良好的“验证”选择,如果用户取消未来的选择,则恢复原来的选择。这固然不是最漂亮的解决方案,但它的工作原理:
// save the last good (i.e. validated) selection:
private ProjectClass lastSelectedProj;
// listing of available projects:
private JList list;
// true if current selected project has been modified without saving:
private boolean dirty;
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
if (evt.getValueIsAdjusting()) return;
// first validate this selection, and give the user a chance to cancel.
// e.g. if selected project is dirty show save: yes/no/cancel dialog.
if (dirty) {
int choice = JOptionPane.showConfirmDialog(this,
"Save changes?",
"Unsaved changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE);
// if the user cancels the selection event revert to previous selection:
if (choice == JOptionPane.CANCEL_OPTION) {
dirty = false; // don't cause yet another prompt when reverting selection
list.setSelectedValue(lastSelectedProj, true);
dirty = true; // restore dirty state. not elegant, but it works.
return;
} else {
// handle YES and NO options
dirty = false;
}
}
// on a validated selection event:
lastSelectedProj = list.getSelectedValue();
// proceed to update views for the newly selected project...
}
}
我认为你需要重写JList的setSelectionInterval(...)方法,以便在你的特殊情况下不做任何事情。
在事件发生时处理它已经太晚了。
但setSelectionInterval旁边,仍然有许多JList的其他选择方法。 – 2009-10-13 04:12:00
然后,您将需要重写多个方法。 – camickr 2009-10-13 04:47:20
我建议您实施自定义ListSelectionModel
。
您能否提供一个具体的例子来说明如何去做?因为我有0的想法需要做什么。 – 2009-10-13 03:51:38
尝试'VetoableListSelectionModel'从http://stackoverflow.com/questions/7936064/before-cell-select-jtable-event – xmedeko 2013-11-12 12:32:26
table.setSelectionModel(new DefaultListSelectionModel(){ @Override public void setSelectionInterval(int index0, int index1) { if (dragState==0 && index0==index1 && isSelectedIndex(index0)) { // Deny all clicks that are one row & already selected return; } else { super.setSelectionInterval(index0, index1); } } });
得到你!由于时间不够,我正在使用类似的实现方式。 – 2009-10-28 03:44:54