how to style the selected JTextPane text?

3

What I want is to get the selected text from JTextPane and edit it, for example: change font color, size, and family. The problem is that once I change the selected text once, it does not change anymore. My code is that, it's just changing the color of the letter, I used html (I do not 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());
edtEditor.setText(start+nova+end);
    
asked by anonymous 17.10.2015 / 08:20

1 answer

1

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;
    try{
        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.setForeground(attributes,color);
        StyleConstants.setFontSize(attributes, size);         
    }       
    if (textSelected != null) {            
        try {                                           
            seuJTextPane.getStyledDocument().remove(start,count);              

        } catch (BadLocationException ex) {
            Logger.getLogger(Create.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
             seuJTextPane.getStyledDocument().insertString(start,textSelected , attributes);
             seuJTextPane.select(start, end);
             seuJTextPane.setSelectedTextColor(color);                                  
        } catch (BadLocationException ex) {
             Logger.getLogger(Create.class.getName()).log(Level.SEVERE, null, ex);
        }
    }else{            
        try {
             seuJTextPane.getStyledDocument().insertString(tp.getStyledDocument().getLength()," " , attributes);
        } catch (BadLocationException ex) {
             Logger.getLogger(Create.class.getName()).log(Level.SEVERE, null, ex);
        }
    }        
}
    
16.12.2015 / 18:26