java – how to style selected JTextPane text?


what I want is to take the selected text from JTextPane and edit it, for example: change the font color, size and family. The problem is that after I change the selected text once, it doesn't change anymore. My code is this one, it's just changing the color of the letter, I used html (I don't know if it's the best way).

String textoSelecionado = edtEditor.getText().toString();
nova = textoSelecionado.replace(textoSelecionado,"<span color='red'>"+textoSelecionado+"</span>");
String start = edtEditor.getText().substring(0,edtEditor.getSelectionStart());
String end = edtEditor.getText().substring(edtEditor.getSelectionEnd(),edtEditor.getText().length());


I solved my problem with this method:

 public void styleFont(boolean bold, boolean under, boolean italic,String fontFamaly,Color color, int size,int tipo){        
    String textSelected = null;
    int count = 0;
    int start = 0;
    int end = 0;
        end = seuJTextPane.getSelectionEnd();
        start = seuJTextPane.getSelectionStart();        
        count = seuJTextPane.getSelectedText().length();
        textSelected= seuJTextPane.getSelectedText();            
    }catch(NullPointerException e){


    SimpleAttributeSet attributes = new SimpleAttributeSet();                       
    StyleConstants.setBold(attributes, bold);
    StyleConstants.setUnderline(attributes, under);  
    StyleConstants.setItalic(attributes, italic);
    StyleConstants.setFirstLineIndent(attributes, 400);
    if(tipo == 1){
        StyleConstants.setFontFamily(attributes, fontFamaly);
        StyleConstants.setFontSize(attributes, size);         
    if (textSelected != null) {            
        try {                                           

        } catch (BadLocationException ex) {
            Logger.getLogger(Create.class.getName()).log(Level.SEVERE, null, ex);
        try {
             seuJTextPane.getStyledDocument().insertString(start,textSelected , attributes);
   , end);
        } catch (BadLocationException ex) {
             Logger.getLogger(Create.class.getName()).log(Level.SEVERE, null, ex);
        try {
             seuJTextPane.getStyledDocument().insertString(tp.getStyledDocument().getLength()," " , attributes);
        } catch (BadLocationException ex) {
             Logger.getLogger(Create.class.getName()).log(Level.SEVERE, null, ex);
Scroll to Top