public void find() {
messageLabel.setText(" ") ;
upperPanel.setBackground(MESSAGE_DEFAULT_COLOR) ;
if(!isFindNext && !isFindPrevious){
isHighlighted=false;
String selectedText = textComp.getSelectedText();
if(selectedText!=null && !selectedText.equals("")){
pattern=selectedText;
}
if(!isFindSelection){
String input = JOptionPane.showInputDialog(
"Find what:", pattern);
if(input==null){
input="";
}
pattern=input;
}
}
doFind();
}
private int doFind(){
textComp.requestFocus();
currentCaretPosition = textComp.getCaretPosition();
text = textComp.getText();
if(!pattern.equals("")){
int pos=0;
if(isFindPrevious){
pos = text.toLowerCase().lastIndexOf(pattern.toLowerCase(), currentCaretPosition-pattern.length()-1);
}else{
pos = text.toLowerCase().indexOf(pattern.toLowerCase(), currentCaretPosition);
}
if(pos < 0){
messageLabel.setText("Find has Finished") ;
upperPanel.setBackground(Color.blue) ;
messageLabel.setForeground(Color.white);
textComp.requestFocus();
return 2;//find has finished
}
if(pos>-1){
sp.getHorizontalScrollBar().setValue(0);
textComp.setCaretPosition(pos+pattern.length());
if(!isHighlighted){
isHighlighted=true;
highlight(textComp, pattern);
}
return 3;//found
}
}else{
removeHighlights(textComp);
return 1;//no pattern
}
return 4;//not found
}
// Creates highlights around all occurrences of pattern in textComp
public void highlight(JTextComponent textComp, String pattern) {
// First remove all old highlights
removeHighlights(textComp);
try {
Highlighter hilite = textComp.getHighlighter();
Document doc = textComp.getDocument();
String text = doc.getText(0, doc.getLength());
int pos = 0;
// Search for pattern
while ((pos = text.toLowerCase().indexOf(pattern.toLowerCase(), pos)) >= 0) {
// Add highlight around pattern using private painter
currentHilite = hilite.addHighlight(pos, pos+pattern.length(), textPainter);
isHighlightPresent=true;
pos += pattern.length();
}
} catch (BadLocationException e) {
}
}
Object currentHilite;
// Removes only our private highlights
public void removeHighlights(JTextComponent textComp) {
Highlighter hilite = textComp.getHighlighter();
Highlighter.Highlight[] hilites = hilite.getHighlights();
for (int i=0; i<hilites.length; i++) {
if (hilites[i].getPainter() instanceof TextPainter) {
hilite.removeHighlight(hilites[i]);
}
}
}
// An instance of the private subclass of the default highlight painter
Highlighter.HighlightPainter textPainter = new TextPainter(Color.yellow);
// A private subclass of the default highlight painter
class TextPainter extends DefaultHighlighter.DefaultHighlightPainter {
public TextPainter(Color color) {
super(color);
}
}