Search code examples
javaswingdragjtextpane

alignment using StyledDocument in drag and drop java


I tired from search the solution for this: i want to align text pane from left to right however but drag and drop java this is last code i written :

  ` StyledDocument doc = txtio.getStyledDocument();
    Style style = txtio.addStyle("right",null);
    StyleConstants . setAlignment (style, StyleConstants .ALIGN_RIGHT);

try {

    doc.insertString(0,txtio.getSelectedText(), style);

    }
    catch (BadLocationException ex) { 
    Logger . getLogger ( mswordframe.class.getName() ).log(Level.SEVERE,null, ex);
    }

    txtio.setStyledDocument(doc);`

 txtio : is the name of text pane;

it doesn't work , Sorry i am weak in english


Solution

  • JTextPane supports character and paragraph attributes. Character attributes are for pieces of text and paragraph attributes are for a whole line of text.

    Alignment of text is a paragraph attribute because you can't have part of the text center aligned and part right aligned for the same line of text.

    Try the following:

    SimpleAttributeSet green = new SimpleAttributeSet();
    StyleConstants.setForeground(green, Color.GREEN);
    
    SimpleAttributeSet right = new SimpleAttributeSet();
    StyleConstants.setAlignment(right, StyleConstants.ALIGN_RIGHT);
    
    try
    {
        doc.insertString(0, txtio.getSelectedText(), green);
        doc.setParagraphAttributes(0, 1, right, false);
    }
    catch(Exception e) {}