JTextField.查找并突出显示JTextArea中的单词 [英] JTextField. Find and highlight the word in a JTextArea

查看:117
本文介绍了JTextField.查找并突出显示JTextArea中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个代码来查找和突出显示JTextArea中的单词,遇到一个问题,我太累了,头疼不已,看不到我的错误. 我有一个搜索栏(TextField),可以在其中输入单词,并且该单词在我的TextArea中得到突出显示.问题是,当我按下" ENTER "键后,TextField被取消选择,因此我必须再次单击它才能找到下一个单词.我想念什么?

I wrote a code to find and highlight a word in a JTextArea and I'm hitting an issue and I'm too tired and with an headache to see my mistake. I have a search bar(TextField) where I can enter a word and the word gets highlighter in my TextArea. Problem is, after I press my "ENTER" key, the TextField gets deselected and I have to click it again to find the next word. What am I missing?

findfieldpage1 = new JTextField();
findfieldpage1.setBounds(37, 295, 63, 24);
gtapage1.add(findfieldpage1);

findfieldpage1.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent evt) {
        int code = evt.getKeyCode();
        if(code == KeyEvent.VK_ENTER){
            String find = findfieldpage1.getText().toLowerCase();
            textpage1.requestFocusInWindow();
            if (find != null && find.length() > 0) {
                Document document = textpage1.getDocument();
                int findLength = find.length();
                try {
                    boolean found = false;
                    if (pos + findLength > document.getLength()) {
                        pos = 0;
                    }
                while (pos + findLength <= document.getLength()) {
                    String match = document.getText(pos, findLength).toLowerCase();
                    if (match.equals(find)) {
                        found = true;
                        break;
                    }
                    pos++;
                }
                if (found) {
                    Rectangle viewRect = textpage1.modelToView(pos);
                    textpage1.scrollRectToVisible(viewRect);
                    textpage1.setCaretPosition(pos + findLength);
                    textpage1.moveCaretPosition(pos);
                    pos += findLength;
                }
            } catch (Exception exp) {
                exp.printStackTrace();
            }
        }
        }
    }
});

推荐答案

方法中的第10行是textpage1.requestFocusInWindow();,这就是为什么它失去焦点的原因,因为您正在将其转移到JTextArea.

Line 10 in your method is textpage1.requestFocusInWindow();, that's why it loses focus, because you're transferring it to the JTextArea.

这篇关于JTextField.查找并突出显示JTextArea中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆