Highlight specific text in JTextArea - Java

186 views Asked by At

I'm trying to quickly highlight my specific text in JTextArea. The code I need is running too slow, and I would like to know if there is a faster way to highlight text without crashing the whole application. I have over 5000 words to scroll through and see if there is a need to highlight them or not, but this code doesn't work great for me. I'm looking for a better way to do it. This is my code:

    class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter 
{

    public MyHighlightPainter(Color color) {
        super(color);
    }
    
}
Highlighter.HighlightPainter myHighlightPainter = new MyHighlightPainter(Color.yellow);

public void Highligh(JTextComponent textComp, String pattern)
{
    try {
        Highlighter hilite = textComp.getHighlighter();
        Document doc = textComp.getDocument();
        String text = doc.getText(0, doc.getLength());
        for(int pos = 0; (pos=text.toUpperCase().indexOf(pattern.toUpperCase(),pos))>=0; pos += pattern.length())
            hilite.addHighlight(pos, pos+pattern.length(), myHighlightPainter);
    } catch (Exception e) {}
}

                public void keyReleased(KeyEvent arg0) {
                
                 String text = vocabolario.getText();
                 String[] parziale = new String[5000];
                 try {
                        String p1 = "SELECT definizione FROM Cherubini WHERE definizione LIKE '%", p2 = "%';", px = vocabolario.getText(), query = p1+px+p2;
                        ResultSet rs =  Main.conn().createStatement().executeQuery(query);
                       
                        while(rs.next())
                        {
                             String[] dati =  { rs.getString("definizione") };
                             for(int i = 0; i < dati.length; i++) { parziale[i] = dati[i]; textArea.append(parziale[i]+"\n"); }
                        }
                        
                 }
                 catch(SQLException exc) {}
                Highligh(textArea,vocabolario.getText());
            }
        });
1

There are 1 answers

0
camickr On BEST ANSWER
for(int pos = 0; (pos=text.toUpperCase().indexOf(pattern.toUpperCase(),pos))>=0; pos += pattern.length())

Why do you keep converting the data to upper case? This should only be done once:

String upperText = text.toUpperCase();
String upperPattern = pattern.toUpperCase();

for(int pos = 0; (pos = upperText.indexOf(upperPattern, pos)) >= 0; pos += pattern.length())