【发布时间】:2020-10-16 20:05:30
【问题描述】:
我有一个带有滚动窗格的列表框,它按字母顺序加载 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
}
【问题讨论】:
-
1) 为了尽快获得更好的帮助,edit 添加minimal reproducible example 或Short, Self Contained, Correct Example。 2) 请学习常见的 Java 命名法(命名约定 - 例如
EachWordUpperCaseClass、firstWordLowerCaseMethod()、firstWordLowerCaseAttribute,除非它是UPPER_CASE_CONSTANT)并始终如一地使用它。 -
您可以过滤列表,以便仅以字母 R 开头的项目(使用您的示例)出现在列表中。您可以在键入第二个字母时进一步过滤列表。 JList with Text Field Filter Example
-
实际上我只需要将项目全部向上移动而不是过滤掉其他项目,但是感谢 JList 文本字段过滤代码。我现在知道我只需要在 scrollPane 中设置 ViewPosition。
标签: java swing jscrollpane jlist selected