The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.text  [49 examples] > JTextPane  [5 examples]

e989. Inserting Styled Text in a JTextPane Component

See the StyleConstants class for more attributes.
    try {
        // Get the text pane's document
        JTextPane textPane = new JTextPane();
        StyledDocument doc = (StyledDocument)textPane.getDocument();
    
        // Create a style object and then set the style attributes
        Style style = doc.addStyle("StyleName", null);
    
        // Italic
        StyleConstants.setItalic(style, true);
    
        // Bold
        StyleConstants.setBold(style, true);
    
        // Font family
        StyleConstants.setFontFamily(style, "SansSerif");
    
        // Font size
        StyleConstants.setFontSize(style, 30);
    
        // Background color
        StyleConstants.setBackground(style, Color.blue);
    
        // Foreground color
        StyleConstants.setForeground(style, Color.white);
    
        // Append to document
        doc.insertString(doc.getLength(), "Some Text", style);
    } catch (BadLocationException e) {
    }

 Related Examples
e990. Enumerating the Paragraphs of a JTextPane Component
e991. Inserting an Image into a JTextPane Component
e992. Inserting a Component into a JTextPane Component
e993. Customizing Tab Stops in a JTextPane Component

See also: Actions and Key Bindings    Caret and Selection    Events    JEditorPane    JFormattedTextField    JTextArea    JTextComponent    JTextField    Styles   


© 2002 Addison-Wesley.