突出显示JTextArea JAVA SWING

时间:2020-04-22 18:47:39

标签: java swing jbutton jtextfield jtextarea

我正在尝试在Java Swing应用程序中实现在JTextArea中搜索特定单词的按钮。谁能帮助我实现按钮以突出显示下一场和上一场比赛?请同时查看我的searchbutton代码。现在,它可以正常工作。

PS。我想在新线程中运行searchButton。这样就可以了吗?

searchButton.addActionListener(e -> new Thread(() -> {
        int pos = 0;
        // Get the text to find...convert it to lower case for eaiser comparision
        String find = searchField.getText().toLowerCase();
        // Focus the text area, otherwise the highlighting won't show up
        textArea.requestFocusInWindow();
        // Make sure we have a valid search term
        if (find != null && find.length() > 0) {
            Document document = textArea.getDocument();
            int findLength = find.length();
            try {
                boolean found = false;
                // Rest the search position if we're at the end of the document
                if (pos + findLength > document.getLength()) {
                    pos = 0;
                }
                // While we haven't reached the end...
                // "<=" Correction
                while (pos + findLength <= document.getLength()) {
                    // Extract the text from the docuemnt
                    String match = document.getText(pos, findLength).toLowerCase();
                    // Check to see if it matches or request
                    if (match.equals(find)) {
                        found = true;
                        break;
                    }
                    pos++;
                }
                // Did we find something...
                if (found) {
                    // Get the rectangle of the where the text would be visible...
                    Rectangle viewRect = textArea.modelToView(pos);
                    // Scroll to make the rectangle visible
                    textArea.scrollRectToVisible(viewRect);
                    // Highlight the text
                    textArea.setCaretPosition(pos + findLength);
                    textArea.select(pos, pos + findLength);
                    textArea.grabFocus();

                }

            } catch (Exception exp) {
                exp.printStackTrace();
            }
        }
    }));

2 个答案:

答案 0 :(得分:1)

有两种方法可以在文本中搜索JTextArea中的匹配项:

  1. 在文档文本上使用String.indexOf(idx)[前进]和String.lastIndexOf(idx)[后退],其中idx是当前插入符号的位置。如果您不希望搜索区分大小写,则可能还需要在搜索文本和文档文本上都使用String.toUppercase / toLowercase。

  2. 使用Matcher / Pattern进行正则表达式搜索。这是更强大但更复杂的解决方案。仅供参考,我正在努力推出DHTML解决方案,并且在最长的时间内,我想包括正则表达式搜索。但是最后我没有-我不认为客户(除非他们是内部客户)关心学习如何编写正则表达式

答案 1 :(得分:0)

  1. 不使用线程。您仅将线程用于耗时的任务。搜索文本字符串不是一项耗时的任务。另外,需要在EDT上完成对Swing组件的更新。因此,您希望突出显示在EDT上完成。

  2. 不要使用grabFocus()。您已经使用了requestFocusInWindow(),这是可以使用的正确方法。

  3. 使用def start_stop_websocket(switch): global conn_key if switch == 'on': bm.start() print('started') if switch == 'off': bm.stop_socket(conn_key) bm.close() print('stoped') 方法(由@ControlAltDel建议)。这样就无需循环代码。您只需从当前插入符号位置搜索文本,要么找到单词,要么找不到单词。

对于我有什么价值,我碰巧有旧代码可以这样做:

String.indexOf(…)

不需要滚动逻辑,选择文本后它将自动滚动。

如果您想通过滚动来欣赏,可以将包含文本的行“居中”。请查看Text Utilities,以获取一些帮助您执行此操作的帮助方法。

注意,最好从文档而不是组件中获取文本。文档中的文本仅在行字符串的末尾包含“ \ n”字符串。这意味着它将同时适用于JTextArea和JTextPane。有关更多信息,请参见:Text and New Lines