【问题标题】:Moving selected item in JScrollPane to top of list and show remaining items in java将 JScrollPane 中的选定项目移动到列表顶部并在 java 中显示剩余项目
【发布时间】: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 exampleShort, Self Contained, Correct Example。 2) 请学习常见的 Java 命名法(命名约定 - 例如EachWordUpperCaseClassfirstWordLowerCaseMethod()firstWordLowerCaseAttribute,除非它是 UPPER_CASE_CONSTANT)并始终如一地使用它。
  • 您可以过滤列表,以便仅以字母 R 开头的项目(使用您的示例)出现在列表中。您可以在键入第二个字母时进一步过滤列表。 JList with Text Field Filter Example
  • 实际上我只需要将项目全部向上移动而不是过滤掉其他项目,但是感谢 JList 文本字段过滤代码。我现在知道我只需要在 scrollPane 中设置 ViewPosition。

标签: java swing jscrollpane jlist selected


【解决方案1】:

我想做的是将所选项目移到列表顶部

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

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

或者另一种选择是实际过滤列表中的项目。您可以通过使用单个列 JTable 以及您的 JTextField 来做到这一点。请阅读 Sorting and Filtering 上的 Swing 教程中的部分以获取工作示例。

【讨论】:

  • 完美!这就是我所需要的。我知道必须有一种相当简单(一两行代码)的方法来做到这一点。
猜你喜欢
  • 2022-11-14
  • 1970-01-01
  • 2021-11-20
  • 2021-04-27
  • 1970-01-01
  • 2010-12-12
  • 1970-01-01
  • 1970-01-01
  • 2021-10-21
相关资源
最近更新 更多