Sunday, June 3, 2012

add different colours to fonts in java


public class Main {
public static void main(String[] args) {
    JTextPane textPane = new JTextPane();
    StyledDocument doc = textPane.getStyledDocument();

    Style style = textPane.addStyle("I'm a Style", null);
    StyleConstants.setForeground(style, Color.red);

    try { doc.insertString(doc.getLength(), "BLAH ",style);} //print "BLAH" in red
    catch (BadLocationException e){}

    StyleConstants.setForeground(style, Color.blue);

      try { doc.insertString(doc.getLength(), "BLEH",style);}   //print "BLEH" in blue
    catch (BadLocationException e){}

    JFrame frame = new JFrame("Test");
    frame.getContentPane().add(textPane);
    frame.pack();
    frame.setVisible(true);
}
}

0 comments:

Post a Comment