簡體   English   中英

在JScrollPane上設置插入符位置

[英]Set caret position on JScrollPane

我在JScrollPane中有一個JEditoPane。 我有一些包含一些預定義標記的文本內容。 我將這些標記的位置存儲在數據庫中。 當我將文本內容設置到JEditorPane中時,我將標記嵌入HTML。 我還添加了HTML換行符來格式化內容。

現在,當我想滾動到突出顯示的標記之一時出現問題。 使用setCaretPosition(int)時,我存儲在數據庫中的令牌的起始位置似乎不匹配。 我知道這可能是因為我在JEditorPane Document中的內容是與HTML混合在一起的。

那么,有沒有一種方法可以在JEditorPane內容中搜索一個String,然后以某種方式獲得找到該字符串的插入符號位置?

這就是您的操作方式(忽略不使用最佳實踐;))-

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的結果存儲在數據庫中。

琴弦有什么共同點嗎? 如果這樣做,則可以嘗試使用java.util.scanner或/和java.util.regex.Matcher的組合。 確保獲得所需的正確正則表達式。 找到字符串后,請獲取第一個字母的indexOf並將其插入位置設置為它。

Java掃描儀

Java Matcher

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM