0
votes

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
One comment I have is why do you keep converting your "text" and "pattern" to upper case? These should be done once outside the loop. If this doesn't help then post a proper minimal reproducible example that demonstrates your problem. Note we don't have access to your database so you will need to manually generate your data. For example many you haven an Array of 10 words of different lengths. Then you randomly append a word to the text area until you have added 5,000 words. - camickr

1 Answers

0
votes
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())