问题描述
我有一个带有滚动窗格的列表框,该列表框按字母顺序列出了100多个歌曲标签。我可以滚动到一首歌曲或输入全名,以在列表中找到要查找的内容。
我要添加的方法是,只需键入首个字母,然后将索引移至该条目,即可更轻松地在此长列表中查找歌曲。我已经用下面的代码完成了此操作,但是发生的事情是标识,选择了字母“ r”的第一个项目(例如),然后将其强制显示在窗格中,但是我想做的是选择该项目项目移到列表顶部,然后拖动与之对齐的下一个项目。
searchByLetter.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
char c;
String s = (letterField.getText().toupperCase());
if(s != null) {
c = s.charat(0);
// the line below sends the typed letter to the method listed & returns where in the
// list the first item with the identified letter is,then the following lines
// 'select it' and make it visible in the pane
indexnumber = GetSongList.getListIndexnumber(c);
}
letterField.setText(null);
list.setSelectedindex(indexnumber);
list.ensureIndexIsVisible(indexnumber);
// what I need Now is a way to move this selected item to the top of the list dragging
// the next items in the list after it
}
解决方法
我想做的是让所选项目移至列表顶部
您实际上并没有更改模型中的数据。而是在滚动窗格中更改视口的位置:
Point p = list.indexToLoction( indexNumber );
scrollPane.getViewport.setViewPosition( p );
或者另一个选择是实际过滤列表中的项目。您可以通过与您的JTable
一起使用单个列JTextField
来做到这一点。阅读Sorting and Filtering的Swing教程中的部分,以获取工作示例。