Java Swing How to - Find the offset to a String in JTextPane and highlight








Question

We would like to know how to find the offset to a String in JTextPane and highlight.

Answer

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
//from   w w w  .  ja v  a2s .  com
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class Main {
  public static void main(String[] args) {

    TextPaneAttributes frame = new TextPaneAttributes();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);

  }
}

class TextPaneAttributes extends JFrame {

  public TextPaneAttributes() {
    JTextPane textPane = new JTextPane();
    StyledDocument doc = textPane.getStyledDocument();
    MutableAttributeSet standard = new SimpleAttributeSet();
    
    StyleConstants.setAlignment(standard, StyleConstants.ALIGN_CENTER);
    doc.setParagraphAttributes(0, 0, standard, true);
    MutableAttributeSet keyWord = new SimpleAttributeSet();
    
    StyleConstants.setForeground(keyWord, Color.red);
    StyleConstants.setItalic(keyWord, true);
    
    textPane.setText("this is a test. \nthis is a four.");
    
    doc.setCharacterAttributes(0, 3, keyWord, false);
    doc.setCharacterAttributes(19, 4, keyWord, false);
    try {
      doc.insertString(0, "Start of text\n", null);
      doc.insertString(doc.getLength(), "End of text\n", keyWord);
    } catch (Exception e) {
    }
    MutableAttributeSet selWord = new SimpleAttributeSet();
    
    StyleConstants.setForeground(selWord, Color.RED);
    StyleConstants.setItalic(selWord, true);
   
    JScrollPane scrollPane = new JScrollPane(textPane);
    scrollPane.setPreferredSize(new Dimension(200, 200));
    add(scrollPane);

    JButton toggleButton = new JButton("Find 'four'");
    toggleButton.addActionListener(e ->{ 
        int index = textPane.getText().indexOf("four");
        StyledDocument doc1 = textPane.getStyledDocument();
        doc1.setCharacterAttributes(index, 4, selWord, false);
      }
    );
    add(toggleButton, BorderLayout.SOUTH);
  }
}