我有一个 JList 并注册了一个选择处理程序(ListSelectionListener)。现在我需要之前选择的项目/索引。
到目前为止,我自己保存最后选择的项目。有更好的方法吗?换句话说:有没有我多年来怀念的方法/最佳实践?!
我有一个 JList 并注册了一个选择处理程序(ListSelectionListener)。现在我需要之前选择的项目/索引。
到目前为止,我自己保存最后选择的项目。有更好的方法吗?换句话说:有没有我多年来怀念的方法/最佳实践?!
我的清单之一是单选。就像克娄巴特拉说的。事件数据在这里没有帮助。
那不是克利奥帕特拉所说的。事件数据确实有帮助。您不能假设第一个索引代表选定的行,而最后一个索引代表前一行。
正如 Kleopatra 建议的那样,您需要做进一步的检查。就像是:
public void valueChanged(ListSelectionEvent e)
{
JList list = (JList)e.getSource();
int selected = list.getSelectedIndex();
int previous = selected == e.getFirstIndex() ? e.getLastIndex() : e.getFirstIndex();
System.out.println();
System.out.println("Selected:" + selected);
System.out.println("Previous:" + previous);
}
您无需编写自定义代码即可将先前选定的项目存储在列表中。JList 提供了一个 ListSelectionListener 它将为您完成工作。这是获取最后一个选定项目的方法。
customList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent arg0) {
// TODO Auto-generated method stub
//Previous Selected Item index will be obtained by arg0.getFirstIndex()
// Similarly Currently Selected Item index will be obtained by this method arg0.getLastIndex()
}
});