2

我在 JScrollPane 中有一个 JEditoPane。我有一些包含一些预定义标记的文本内容。我将这些令牌的位置存储在数据库中。当我将文本内容设置到 JEditorPane 中时,我使用 HTML 嵌入了标记。我还添加了 HTML 换行符来格式化内容。

现在,当我想滚动到突出显示的标记之一时,问题就来了。使用 setCaretPosition(int) 时,我存储在数据库中的标记的起始位置似乎不匹配。我知道这可能是因为我在 JEditorPane Document 中的内容与 HTML 混合在一起。

那么有没有办法在 JEditorPane 内容中搜索字符串,然后以某种方式获取找到该字符串的插入符号位置?

4

2 回答 2

1

这就是你的做法(忽略不使用最佳实践;)) -

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();
        }
    }
}

这就是结果:

在此处输入图像描述

您应该将结果存储indexof在数据库中。

于 2013-07-25T16:48:15.997 回答
0

字符串有什么共同点吗?如果他们这样做,您可以尝试使用 java.util.scanner 或/和 java.util.regex.Matcher 的组合。确保根据您的需要获得正确的正则表达式。找到字符串后,获取第一个字母的 indexOf 并将插入符号位置设置为它。

Java 扫描仪

Java 匹配器

于 2013-07-25T16:27:43.877 回答