Java 在JScrollPane上设置插入符号位置
我把绝地烷放在一块玻璃板里。我有一些包含一些预定义标记的文本内容。我正在数据库中存储这些令牌的位置。 当我将文本内容设置到JEditorPane中时,我将标记嵌入HTML。我还添加了HTML换行符来格式化内容 现在,当我想滚动到突出显示的标记之一时,问题来了。在使用setCaretPosition(int)时,我存储在数据库中的令牌的起始位置似乎不匹配。我知道这可能是因为我在JEditorPane文档中的内容混合了HTMLJava 在JScrollPane上设置插入符号位置,java,html,swing,jtextpane,caret,Java,Html,Swing,Jtextpane,Caret,我把绝地烷放在一块玻璃板里。我有一些包含一些预定义标记的文本内容。我正在数据库中存储这些令牌的位置。 当我将文本内容设置到JEditorPane中时,我将标记嵌入HTML。我还添加了HTML换行符来格式化内容 现在,当我想滚动到突出显示的标记之一时,问题来了。在使用setCaretPosition(int)时,我存储在数据库中的令牌的起始位置似乎不匹配。我知道这可能是因为我在JEditorPane文档中的内容混合了HTML 那么,有没有一种方法可以在JEditorPane内容中搜索字符串,然后以
那么,有没有一种方法可以在JEditorPane内容中搜索字符串,然后以某种方式获取找到该字符串的插入符号位置?这些字符串有什么共同点?如果有,您可以尝试使用java.util.scanner或/和java.util.regex.Matcher的组合。确保为您需要的内容获取正确的正则表达式。找到字符串后,获取第一个字母的索引并设置插入符号位置 您就是这样做的(忽略不使用最佳实践;)-
publicstaticvoidmain(字符串[]args){
final JEditorPane JEditorPane=新的JEditorPane(“text/html”,“这是一些标题,在这个文本之后将是CARRET
这是一些更多的文本
和更多”);
最终JScrollPane JScrollPane=新JScrollPane(jEditorPane);
最终JFrame JFrame=新JFrame(“HHHHHHH”);
jframe.add(jScrollPane);
jframe.setSize(新尺寸(200200));
jframe.setVisible(true);
最终字符串text=jEditorPane.getText();
最终int索引=text.indexOf(“T”);
jEditorPane.setCaretPosition(索引+1);
while(true){
试一试{
线程。睡眠(1000000);
}捕捉(中断异常e){
e、 printStackTrace();
}
}
}
这就是结果:
您应该将indexof
的结果存储在数据库中
public static void main( String[] args ) {
final JEditorPane jEditorPane = new JEditorPane( "text/html", "<h1>This is some header</h1>After this text would be the CARRET<br>This is some more text<br>And more" );
final JScrollPane jScrollPane = new JScrollPane( jEditorPane );
final JFrame jframe = new JFrame( "HHHHHH" );
jframe.add( jScrollPane );
jframe.setSize( new Dimension( 200, 200 ) );
jframe.setVisible( true );
final String text = jEditorPane.getText();
final int index = text.indexOf( "T" );
jEditorPane.setCaretPosition( index + 1 );
while ( true ) {
try {
Thread.sleep( 1000000 );
} catch ( InterruptedException e ) {
e.printStackTrace();
}
}
}