2

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();
            }
        }
        }
    }
});
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
MrSilent
  • 564
  • 10
  • 28
  • 1
    If you want help, you'll have to provide an [SSCCE](http://sscce.org) that demonstrates the problem. Without that, the best advice we can give you is to get some rest and look at this with fresh eyes afterwards. – Kevin Workman Jan 09 '14 at 16:10
  • 1
    By deselected you mean it loses focus, or the text inside isn't selected? – rhobincu Jan 09 '14 at 16:17
  • @KevinWorkman I'll follow your advice and get some sleep. – MrSilent Jan 09 '14 at 16:19
  • @rhobincu It loses focus, the text inside is selected but it loses focus. – MrSilent Jan 09 '14 at 16:19
  • 1) For better help sooner, post an [SSCCE](http://sscce.org/). Note the document is being reviewed and discussed on [this question](http://meta.stackexchange.com/q/214955/155831), contributions welcome. 2) For Swing, typically use key bindings over the AWT based, lower level, `KeyListener`. See [How to Use Key Bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) for details on how to use them. ... – Andrew Thompson Jan 09 '14 at 16:22
  • ... 3) Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556), along with layout padding & borders for [white space](http://stackoverflow.com/q/17874717/418556). – Andrew Thompson Jan 09 '14 at 16:22
  • @Andrew Thompson 1. I'm think DocumentListener, 2. code example about topics were removed from official tutorial during big clean up, 3. too lazy to answering - my long status, 4. cloudy & cold weather will be here == Kevin Workman is here, without any changes from SunForums :-) – mKorbel Jan 09 '14 at 16:37

4 Answers4

2

Youre not transfering the focus back to the text field after the search is done

Add at the end: Jtextfield.requestfocus()

Typo
  • 1,875
  • 1
  • 19
  • 32
2

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

rhobincu
  • 906
  • 1
  • 7
  • 22
0

In the end, to avoid the hassle. I added a JButton and changed the keyPressed to an actionPerformed. So everytime I click that button, it finds and highlights me the string I enter in the TextField. Thank you for your help guys, I appreciate it.

MrSilent
  • 564
  • 10
  • 28
0

Add one more listener to textarea. After the focus is shifted to text area, this way it'll remain in textarea and the event (enter key press) etc will make the search happen.

/search filed begins/

    JTextField findtext = new JTextField();
    //findtext.setBounds(112,549, 63, 24);
    frame.add(findtext,BorderLayout.BEFORE_FIRST_LINE);

    findtext.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent evt) {
            int code = evt.getKeyCode();

            if(code == KeyEvent.VK_ENTER){
                String find = findtext.getText().toLowerCase();
                tarea.requestFocusInWindow();
                //findtext.requestFocus();
                //findtext.requestFocusInWindow();
                if (find != null && find.length()> 0) {
                    Document document = tarea.getDocument();
                    int findLength = find.length();
                    try {
                         //int pos=0;
                         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 = tarea.modelToView(pos);
                        tarea.scrollRectToVisible(viewRect);
                        tarea.setCaretPosition(pos + findLength);
                        tarea.moveCaretPosition(pos);
                        pos += findLength;
                        //Thread.sleep(2000);
                      //  findtext.requestFocusInWindow();

                    }

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

                 }//findtext.requestFocusInWindow();
        }
    });

    /*control back to textarea*/
    tarea.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent evt) {
            int code = evt.getKeyCode();

            if(code == KeyEvent.VK_ENTER){
                String find = findtext.getText().toLowerCase();
                tarea.requestFocusInWindow();
                //findtext.requestFocus();
                //findtext.requestFocusInWindow();
                if (find != null && find.length()> 0) {
                    Document document = tarea.getDocument();
                    int findLength = find.length();
                    try {
                         //int pos=0;
                         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 = tarea.modelToView(pos);
                        tarea.scrollRectToVisible(viewRect);
                        tarea.setCaretPosition(pos + findLength);
                        tarea.moveCaretPosition(pos);
                        pos += findLength;
                        //Thread.sleep(2000);
                      //  findtext.requestFocusInWindow();

                    }

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

                 }//findtext.requestFocusInWindow();
        }
    });


    /*search filed ends*/