IndexOutOfBounds
is maybe from doc.getStyle("exampleStyle")
, by using MutableAttributeSet works for me,
can you demonstrated your issue with IndexOutOfBounds
by using this SSCCE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class TextPaneAttributes extends JFrame {
private static final long serialVersionUID = 1L;
public TextPaneAttributes() {
final JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
final 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("one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\n");
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) {
}
final MutableAttributeSet selWord = new SimpleAttributeSet();
StyleConstants.setForeground(selWord, Color.blue);
StyleConstants.setItalic(selWord, true);
JScrollPane scrollPane = new JScrollPane(textPane);
scrollPane.setPreferredSize(new Dimension(200, 200));
add(scrollPane);
JToggleButton toggleButton = new JToggleButton("where is 'four'");
toggleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
//AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
//boolean selected = abstractButton.getModel().isSelected();
int index = textPane.getText().indexOf("four");
StyledDocument doc = textPane.getStyledDocument();
doc.setCharacterAttributes(index, 4, selWord, false);
}
});
add(toggleButton, BorderLayout.SOUTH);
}
public static void main(String[] args) {
Runnable doRun = new Runnable() {
@Override
public void run() {
TextPaneAttributes frame = new TextPaneAttributes();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(doRun);
}
}