Java JTable 转到行错误

标签 java focus jtable goto tablecell

我有一个 find 函数,可以在包含数千个条目的 JTable 中查找字符串。 Michael Meyers他很友善地帮助我解决了该函数的 goto 部分。不过似乎有一个错误...

当用户搜索字符串时,应用程序会在 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 行,但完整版本中情况并非总是如此。

Demo.jar

即使这个演示的代码仍然只有几百行,所以下面是我认为相关的部分。

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;
        }
    }

    ...
}

最佳答案

Sometimes it will jump 10+ lines short of the line I am looking for and I need to scroll down to see it.

发布您的SSCCE这说明了问题所在。您可以创建一个包含一千行的表格,然后使用 setValueAt(...) 方法用您要搜索的文本填充一些随机单元格。

Is it possible to focus the selected entry in the center of the visible area?

您需要调整要滚动到的行号。也就是说,如果您向下搜索,则需要从行号中减去“x”,以便视口(viewport)位于包含文本的行之前的一行上。

关于Java JTable 转到行错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4632742/

相关文章:

java - 如何在 .txt 文件中存储字符串,同时不清除该文件中已有的内容 java

java - K 个分区子数组之和的最大值

java - JTreeTable 更新

javascript - 焦点位于输入字段

java - 如何将 Action 列表器添加到 jmenuitem

java - 如何检测对 JTable 行边界的点击?

java - JOGL 小程序与 WebGL

java - 我应该在多线程程序中使用连接池吗?

vb.net - 在DataGridView中获取行号

JavaScript 手动调度 mousedown 不会使文本框散焦