我一直在研究通过点击特定单词的按钮找到下一个项目的项目,但是它一直在抛出异常?!
public void highlightnext(JTextComponent textareafield,String pattern) {
textareafield.getHighlighter().removeAllHighlights();
//highlighting
try {
hilit = textarea.getHighlighter();
painter = new DefaultHighlighter.DefaultHighlightPainter(HILIT_COLOR);
Document doc=textarea.getDocument();
String area=doc.getText(0, doc.getLength());
if (pos>area.length())
return;
pos=(area.toUpperCase().indexOf(pattern.toUpperCase(),pos));
pos=(area.toUpperCase().indexOf(pattern.toUpperCase(),pos+1));
hilit.addHighlight(pos,pos+pattern.length(), painter);
System.out.println(pos);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
pos=(area.toUpperCase().indexOf(pattern.toUpperCase(),pos));
pos=(area.toUpperCase().indexOf(pattern.toUpperCase(),pos+1));
每次效率不高时,都不要将数据转换为大写。将文本转换为字符串,然后在代码中使用这两个字符串。
不确定为什么你有两个陈述。您只需要一个人进行搜索。
您需要检查" pos"的值确保它不是" -1"
以下是一些示例代码。它找到所有出现的文本:
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class TextAndNewLinesTest extends JFrame
{
public TextAndNewLinesTest()
throws Exception
{
String text =
"one two three four five\r\n" +
"one two three four five\r\n" +
"one two three four five\r\n" +
"one two three four five\r\n" +
"one two three four five\r\n";
JTextPane textPane = new JTextPane();
textPane.setText(text);
JScrollPane scrollPane = new JScrollPane( textPane );
getContentPane().add( scrollPane );
Highlighter.HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter( Color.cyan );
String search = "three";
int offset = 0;
int length = textPane.getDocument().getLength();
text = textPane.getDocument().getText(0, length);
//text = textPane.getText();
while ((offset = text.indexOf(search, offset)) != -1)
{
try
{
textPane.getHighlighter().addHighlight(offset, offset + 5, painter); // background
offset += search.length();
}
catch(BadLocationException ble) {}
}
}
public static void main(String[] args)
throws Exception
{
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new TextAndNewLinesTest();
frame.setTitle("Text and New Lines - Problem");
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.setSize(400, 120);
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
如果你只想一次找到一个事件,那么基本上你会改变"而#34;陈述到"如果"言。