Search code examples
javaswingjscrollpanejlistselected

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


I have a list box with scroll pane which loads in an alphabetical list of 100+ song tabs. I can scroll to a song or type the full name to find what I'm looking for in the list.

What I am trying to add is a way to find a song in this long list more easily by just typing in the first letter and then have the index move to that item. I have accomplished this with the code below but what happens is the first item with letter 'r' (as an example) is identified, selected and then forced to be visible in the pane, but what I would like to do is have that selected item move to the top of the list and drag the next items in line with it.

 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
    }

Solution

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

    You don't actually change the data in the model. Instead you change the position of the viewport in the scroll pane:

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

    Or another option is to actually filter the items in the list. You could do this by using a single column JTable along with your JTextField. Read the section from the Swing tutorial on Sorting and Filtering for a working example.