Java JTextPane appendAsMessage(JTextPane pane, String fontName, int fontSize, String s)

Here you can find the source of appendAsMessage(JTextPane pane, String fontName, int fontSize, String s)

Description

Appends a given string to the StyledDocument of a pane as a message, that is, using the Style 'MessageStyle'.

License

Open Source License

Parameter

Parameter Description
pane a JTextPane with a StyledDocument .
fontName the name of the font to be used
fontSize The size of the font to be used.
s a String .

Declaration

public static void appendAsMessage(JTextPane pane, String fontName, int fontSize, String s) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.awt.Color;

import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;

import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class Main {
    /**//from   w w  w. j  a v  a  2  s . c  o m
     * Appends a given string to the {@code StyledDocument} of a {@code pane} as
     * a <b>message</b>, that is, using the {@code Style} 'MessageStyle'.
     * <p>
     * This method will create the style if the {@code JTextPane} doesn't
     * already have it.</p>
     *
     * @param pane a {@code JTextPane} with a {@code StyledDocument}.
     * @param fontName the name of the font to be used
     * @param fontSize The size of the font to be used.
     * @param s a {@code String}.
     */
    public static void appendAsMessage(JTextPane pane, String fontName, int fontSize, String s) {
        if (pane.getStyle("MessageStyle") == null) {
            Style messageStyle = pane.addStyle("MessageStyle", null);
            StyleConstants.setForeground(messageStyle, Color.BLACK);
            StyleConstants.setFontFamily(messageStyle, fontName);
            StyleConstants.setFontSize(messageStyle, fontSize);
        }

        StyledDocument doc = (StyledDocument) pane.getDocument();
        try {
            doc.insertString(doc.getLength(), s, pane.getStyle("MessageStyle"));
        } catch (BadLocationException ex) {
        }
    }
}

Related

  1. addStyle(JTextPane textPane, String name, Color foreground)
  2. appendAsGreen(JTextPane pane, String fontName, int fontSize, String s)
  3. appendString(String str, JTextPane jtext)
  4. appendToPane(JTextPane textPane, String text, Color foregroundColor, Color backgroundColor)
  5. applyRegex(String regex, JTextPane pane, Color highlightColor)
  6. centerText(JTextPane pane)