0

I have a JTextPane where I want to add lines and depending on their content have them have a different formatting.

Currently I have this

StyleContext context = new StyleContext();
StyledDocument document = new DefaultStyledDocument(context);

Style styleBold = context.getStyle(StyleContext.DEFAULT_STYLE);
StyleConstants.setBold(styleBold, true);
StyleConstants.setFontSize(styleBold, 18);

Style styleNorm = context.getStyle(StyleContext.DEFAULT_STYLE);
StyleConstants.setFontSize(styleNorm, 15);

for (int i = 0; i < temp.size(); i++) {
    String tmp = temp.get(i);
    if (tmp.substring(0, 2).equals(COMMENT_PREFIX)) {
        String addThis = " - " + tmp.substring(2);

        try {
            document.insertString(document.getLength(), addThis,
                    styleNorm);
        } //CATCH
    } else if (tmp.substring(0, 2).equals(VERSION_PREFIX)) {
        Date d = new Date(System.currentTimeMillis());
        String addThis = "Version: " + tmp.substring(2) + " - "
                + d.toString();
        try {
            document.insertString(document.getLength(), addThis,
                    styleBold);
        } //CATCH
    }
    try {
        document.insertString(document.getLength(), "\n", styleNorm);
    } //CATCH
}

I took out the catch statements to reduce code size.

However, this formats my entire text with the styleNorm. Is this because it's the last called Style and they overwrite eachother? If so, how do I fix this?

Kevin Reid
  • 37,492
  • 13
  • 80
  • 108
Adrian Jandl
  • 2,985
  • 4
  • 23
  • 30

1 Answers1

10

Also seen here, TextComponentDemo shows how to apply a number of StyleConstants, including font size, style, alignment and color. The styles may applied either directly to the Document, as shown in initAttributes(), or via the actions of StyledEditorKit, seen here.

Addendum: The example below creates three related styles using SimpleAttributeSet. Note that highAlert alters the color but retains the bold attribute inherited from boldBlue.

image

import java.awt.Color;
import java.awt.EventQueue;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

/**
 * @see https://stackoverflow.com/a/15600689/230513
 */
public class Test {

    private void display() throws BadLocationException {
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        String s = new Date().toString();
        JTextPane jtp = new JTextPane();
        StyledDocument doc = (StyledDocument) jtp.getDocument();

        SimpleAttributeSet normal = new SimpleAttributeSet();
        StyleConstants.setFontFamily(normal, "SansSerif");
        StyleConstants.setFontSize(normal, 16);

        SimpleAttributeSet boldBlue = new SimpleAttributeSet(normal);
        StyleConstants.setBold(boldBlue, true);
        StyleConstants.setForeground(boldBlue, Color.blue);

        SimpleAttributeSet highAlert = new SimpleAttributeSet(boldBlue);
        StyleConstants.setFontSize(highAlert, 18);
        StyleConstants.setItalic(highAlert, true);
        StyleConstants.setForeground(highAlert, Color.red);

        doc.insertString(doc.getLength(), s + "\n", normal);
        doc.insertString(doc.getLength(), s + "\n", boldBlue);
        doc.insertString(doc.getLength(), s + "\n", highAlert);
        f.add(jtp);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    new Test().display();
                } catch (BadLocationException ex) {
                    ex.printStackTrace(System.err);
                }
            }
        });
    }
}
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 1
    +1 You are really a swing hero. Congrats on exceeding 100K reps. – Eng.Fouad Mar 25 '13 at 16:47
  • how we have combination of **bold** and **italic**. You example basically show bold and italic separately. How i need to print bold and italic for same text. – chinna_82 Nov 25 '13 at 06:28
  • 1
    @chinna_82 - to set both bold and italic for a SimpleAttributeSet ("sas", for example), you just call both 'StyleConstants.setBold( sas, true )' and 'StyleConstants.setItalic( sas, true )'. – marklark Oct 26 '17 at 18:43