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