[英]Highlight specific text in JTextArea - Java
I'm trying to quickly highlight my specific text in JTextArea.我试图在 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.
我有超过 5000 个单词要滚动,看看是否需要突出显示它们,但是这段代码对我来说不起作用。 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());
}
});
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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.