I am trying to implement buttons that search a specific word in JTextArea in my Java Swing application. Can anyone help me to implement buttons to highlight the next and previous match ? Please review my code for searchbutton aswell. For now it works fine.
PS. I want run searchButton in new Thread. Is it okay like that ???
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();
}
}
}));