英文:
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);
// 下面的代码将输入的字母发送到所列方法,并返回具有识别字母的首个项目在列表中的位置,
// 然后下面的代码会将其“选择”并确保其在窗格中可见
indexNumber = GetSongList.getListIndexNumber(c);
}
letterField.setText(null);
list.setSelectedIndex(indexNumber);
list.ensureIndexIsVisible(indexNumber);
// 现在我需要的是一种方法,将所选项目移动到列表顶部,并拖动其后的列表项目
}
}
英文:
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
}
答案1
得分: 0
我想要做的是让所选项目移到列表顶部
实际上,您并没有更改模型中的数据。而是更改滚动窗格中视口的位置:
Point p = list.indexToLocation(indexNumber); scrollPane.getViewport().setViewPosition(p);
或者另一种选择是实际上筛选列表中的项目。您可以使用带有您的
JTextField
的单列JTable
来实现这一点。阅读 Swing 教程中关于排序和过滤的部分,其中有一个可工作的示例。
英文:
> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论