我只想看看选择了哪个元素,并根据索引更改了框架上的其他标签和文本字段。我的代码如下:
list = new JList(listModel);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setLayoutOrientation(JList.VERTICAL);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
System.out.println(e.getLastIndex());
}
});单击第一个元素输出:0 0后,单击第二个元素:1 1,然后再次尝试单击第一个元素,但这次的输出又是1 1。当我尝试使用25个元素时,选择last,然后单击first并输出为23 23。是关于事件的问题还是关于我的代码?
发布于 2015-05-08 10:10:38
你得到的行为是标准的行为,如果你想要有不同的行为,创建你自己的SelectionListener,同时考虑getValueIsAdjusting()。
class SharedListSelectionHandler implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
int firstIndex = e.getFirstIndex();
int lastIndex = e.getLastIndex();
boolean isAdjusting = e.getValueIsAdjusting();
output.append("Event for indexes "
+ firstIndex + " - " + lastIndex
+ "; isAdjusting is " + isAdjusting
+ "; selected indexes:");
if (lsm.isSelectionEmpty()) {
output.append(" <none>");
} else {
// Find out which indexes are selected.
int minIndex = lsm.getMinSelectionIndex();
int maxIndex = lsm.getMaxSelectionIndex();
for (int i = minIndex; i <= maxIndex; i++) {
if (lsm.isSelectedIndex(i)) {
output.append(" " + i);
}
}
}
output.append(newline);
}
}找到在这里解释这个例子。
https://stackoverflow.com/questions/30121037
复制相似问题