JTextArea.select() does not select anything

邮差的信 提交于 2019-12-01 14:39:01

Solved it myself. The textarea needs to get the focus right before selecting a word!

textarea.requestFocus();

Here is the search function with the new line of code:

void search() {
    searchstr = tf_search.getText();
    if (searchstr == null) {
        return;
    }

    aktStr = textarea.getText();
    Index = aktStr.indexOf(searchstr);

    if (Index == -1) {
        JOptionPane.showMessageDialog(null, "String not found", "Dialog", JOptionPane.INFORMATION_MESSAGE);
    } else {
        textarea.requestFocus();
        textarea.select(Index, Index + searchstr.length());
    }
}

I tested you code and it didn't work for me either. The issue is that the JComponent needs focus in order to show any cursor selections. So if you just call

textarea.requestFocusInWindow();

right before the 'select' method, you should be good. If you don't want the highlighting to be dependent on focus I would go with using the highlighter mentioned in my comments.

The textarea has not the focus. Add textarea.requestFocus(); before you select the text:

    } else {
        textarea.requestFocus();
        textarea.select(Index, Index + searchstr.length());
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!