我有一个查找函数,它可以在包含数千个条目的 JTable 中找到一个字符串。Michael Meyers非常友好地帮助我完成了函数的 goto 部分。不过好像有bug...
当用户搜索字符串时,应用程序正确地在 JTable 中找到该行并将其突出显示。它也试图专注于它,但并非总是如此。有时它会比我正在寻找的行少 10 多行,我需要向下滚动才能看到它。正如我所说,这个 JTable 中有几千个条目,如果我正在搜索某些内容,则很难滚动。是否可以将所选条目集中在可见区域的中心?
if (logs.get(i).getLine().contains(findStr))
{
logTable.scrollRectToVisible(logTable.getCellRect(thisPos, 1, true)); // goto
logTable.setRowSelectionInterval(thisPos, thisPos); // highlight
}
我不确定它是否有帮助,但这里是 JTable 设置代码:
JTable logTable = new JTable(logTableModel);
logTable.setShowGrid(true);
logTable.setShowVerticalLines(true);
logTable.setShowHorizontalLines(false);
logTable.setRowSorter(sorter);
logTable.getSelectionModel().addListSelectionListener(new LogRowListener());
JScrollPane scrollPane = new JScrollPane();
scrollPane.getViewport().add(logTable);
scrollPane.setPreferredSize(new Dimension(800, 450));
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
谢谢
编辑 下面是下载 .jar 文件的链接。此文件是说明问题的代码的有限版本。这个版本似乎总是跳短 2-3 行,但在完整版中并非总是如此。
即使这个演示的代码仍然只有几百行,所以下面是我认为相关的部分。
public class Proto extends JFrame implements ActionListener
{
public Proto() { ... }
@Override
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if (BUTTON_NEXT_FIND.equals(command))
{
findNext();
}
}
...
private void findNext()
{
String findStr = findField.getText();
int pos = selectedLogRow;
// if we're searching for the same string again step forward once
if (pos == lastFoundPos)
++pos;
// search through the log for the string
while (pos < logs.size())
{
if (logs.get(pos).getLine().contains(findStr))
{
logTable.scrollRectToVisible(logTable.getCellRect(pos, 1, true));
logTable.setRowSelectionInterval(pos, pos);
lastFoundPos = pos;
break;
}
++pos;
}
}
...
}