我正在尝试编写自己的ListSelectionModel实现,目前在尝试实现insertIndexInterval
时遇到了麻烦。我不理解Sun / Oracle的DefautListSelectionModel
实现中此方法的结果。这是一个例子:
ListSelectionModel model = new DefaultListSelectionModel();
model.setSelectionInterval(3, 5);
model.addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent e)
{
System.out.println("Changed range reported by event: " +
e.getFirstIndex() + "-" + e.getLastIndex());
}
});
System.out.print("Selected indices before insert: ");
for (int i = model.getMinSelectionIndex(); i <= model.getMaxSelectionIndex(); i++)
if (model.isSelectedIndex(i)) System.out.print(i + " ");
System.out.println();
model.insertIndexInterval(3, 3, true);
System.out.print("Selected indices after insert: ");
for (int i = model.getMinSelectionIndex(); i <= model.getMaxSelectionIndex(); i++)
if (model.isSelectedIndex(i)) System.out.print(i + " ");
System.out.println();
运行此代码时,将获得以下输出:
Selected indices before insert: 3 4 5
Changed range reported by event: 3-8
Selected indices after insert: 3 4 5 6 7 8
因此,初始选择为3-5,并在插入新索引时扩展为3-8。但是已经选择了3-5,所以真正的变化只有6-8,那么为什么事件告诉我3-8的范围已经改变?当您将
insertIndexInterval
调用更改为以下内容时,这更加令人困惑:model.insertIndexInterval(3, 3, false);
现在的输出是这样的:
Selected indices before insert: 3 4 5
Changed range reported by event: 5-8
Selected indices after insert: 3 4 5 6 7 8
我不知道为什么报告的更改是5-8。
该方法的API文档太短,无法理解正在发生的事情。尤其是这个
before
参数对我来说是个谜,因为它对选择没有任何影响,但似乎对事件以及前导和锚定索引有影响。我什至不能为实现编写一个单元测试,因为我根本不知道预期的结果。
因此,有人可以详细解释此方法(尤其是
before
标志)的作用以及对选择模型和ListSelectionEvent
的副作用吗? 最佳答案
将新数据添加到数据模型时使用它(因此应移动当前选择索引)。如果2表示“新添加并选中”,则输出为:
[0,0,0,1,1,1,0,0,0,0] == [3A,4,5L]
-> add after [0,0,0,1,2,2,2,1,1,0] == [3A,4,5,6,7,8L]
-> add before [0,0,0,2,2,2,1,1,1,0] == [3,4,5,6A,7,8L]
您在此处看到的是DefaultListSelectionModel的功能*-在当前选择中添加索引,会自动扩展选择。
首先选择索引1,然后在索引3插入三行:
[1,0,0,0,0,0,0,0,0,0]
-> add after [1,0,0,0,0,0,0,0,0,0]
请注意,您的选择表示形式具有误导性,零实际上并不存在。打印选择状态的更好方法是:
private static void printSelection(ListSelectionModel model) {
System.out.print("[");
for (int i = model.getMinSelectionIndex(); i <= model.getMaxSelectionIndex(); i++) {
if(i > model.getMinSelectionIndex()) {
System.out.print(",");
}
if(model.isSelectedIndex(i)) {
System.out.print(i);
if(i == model.getAnchorSelectionIndex()) {
System.out.print("A");
}
if(i == model.getLeadSelectionIndex()) {
System.out.print("L");
}
}
}
System.out.println("]");
}
*)DefaultListSelectionModel#insertIndexInterval的文档与界面不同,另请参见http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4700643和http://java.net/jira/browse/SWINGX-272