将 JScrollPane 中的选定项目移动到列表顶部并在 java 中显示剩余项目

Moving selected item in JScrollPane to top of list and show remaining items in java

我有一个带有滚动窗格的列表框,它加载了按字母顺序排列的 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
    }

I would like to do is have that selected item move to the top of the list

您实际上并没有更改模型中的数据。相反,您可以更改视口在滚动窗格中的位置:

Point p = list.indexToLoction( indexNumber );
scrollPane.getViewport.setViewPosition( p );

或者另一种选择是实际过滤列表中的项目。您可以通过使用单列 JTable 和您的 JTextField 来完成此操作。阅读 Swing 教程中关于 Sorting and Filtering 的部分以获得工作示例。