Set font color to JTextPane

I wrote a small program only 70 lines. These codes traverse all the text line by line, show all digits in blue color, but I do not know why, you see, there is something wrong, some characters are not updated correctly. but why?
import javax.swing.*;
import java.awt.Color;
import javax.swing.text.*;
public class MainWnd extends JFrame{
private JTextPane textPane = new JTextPane();
public MainWnd() {
getContentPane().add(textPane);
textPane.setText("1234567890\r\n1234567890\r\n1234567890\r\n1234567890\r\n1234567890\r\n");
setBounds(100, 100, 400, 400);
formatHighlight(textPane);
show();
public void formatHighlight(JTextPane textPane) {
String text = textPane.getText();
int begin = 0;
int end = text.length() - 1;
System.out.println("First, set all text black color: begin:" + begin + " end:" + end);
System.out.println("All text is #" + text.substring(begin, end + 1)+"#");
//reset all as default color black
setTextColor(textPane, begin, end + 1, Color.BLACK);
for (int i = begin; i <= end; ) {
char c = text.charAt(i);
//digital
if (Character.isDigit(c)) {
i = transactDigit(textPane, text, i);
continue;
//others
System.out.println("skip others at i:" + i + " c:" + c);
i++;
private void setTextColor(final JTextPane sourcePane,
final int offset, final int endPos, final Color color) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MutableAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setForeground(attr, color);
if (offset != endPos) {
StyledDocument doc = (StyledDocument) sourcePane.getDocument();
doc.setCharacterAttributes(offset, endPos - offset, attr, false);
private int transactDigit(JTextPane sourcePane, String text, int offset) {
int endPos = 0;
for (endPos = offset; endPos < text.length(); endPos++) {
char c = text.charAt(endPos);
if (!Character.isDigit(c))
break;
System.out.println("set digit blue color from " + offset + " to " + (endPos-1));
System.out.println("The digit string is #" + text.substring(offset, endPos) + "#");
setTextColor(sourcePane, offset, endPos, Color.BLUE);
return endPos;
public static void main(String[] args) {
MainWnd mainWnd = new MainWnd();
Pls, help!

I have found the reason. replace
String text = textPane.getText();
with
String text = textPane.getDocument().getText(0, textPane.getDocument().getLength());
It's because the document (model) does not contain '\r', but the view does.
Thx for your enthusiasm.

Similar Messages

  • Setting Font Color and Bold Property in ALV Grid

    I have a requirement to set the font in particular ALV Cells  in red color.
    Also this font (text) has to be set to Bold.
    I know how to set cell coloring in ALV Grid, but have no idea regarding how to set font color.
    Could please give me an idea/code segment/suggestion.
    Thank You!

    Please refer this post
    Coloring of ROWS in ALV tree

  • WLC AireOS 8.0 - how to set font-color for integrated webauth/weblogin?

    Hello,
    up to AireOS 7.6 I was able to set the font-color of the internal webauth/weblogin page using html-codes, for example like this:
    Headline: Welcome to our <font color="red">guest</font>-network!
    Message: You need a valid <font color="blue">user</font> to login.
    Now with AireOS 8.0 this doesn't work anymore. When I try to set a headline or message with font-tags I get "Error while setting headline." (or "...message.") when I hit apply. I have to remove the font-tag to save the weblogin page.
    #CLIWEB-6-CLIWEB_INVALID_HTML_TAGS_USED: [PA] cli_web_api.c:1748 The Customization message field has invalid html tags
    #CLIWEB-6-CLIWEB_INVALID_HTML_TAGS_USED: [PA] cli_web_api.c:1663 The Headline field has invalid html tags
    So, how can we now set different font colors/styles like in previous releases? Using external or uploading selfmade pages is not an option.
    Thanks,
    Chris

    Since your using code to change the default internal portal page look, its better for you just to create a custom webauth and upload that to the WLC.  That is how I do my implementations as its easier for me to create a new page than trying to mess around with the internal page.  As you can see, Cisco can change the way things work in every version.  It might just be the fact that they no longer are allowing html code to be inserted in the default webauth/passthrough page.
    Scott

  • Set font color for the JTextField

    I'm using JTextField in my project. However, can anybody teach me how to set the font color for the font in the JTextField to other color. The default font color is black. Any idea about this?

    JTextField field = new JTextField(20);
    field.setForeground(Color.blue);
    Good luck ;)

  • How to set font Color in Mail

    Sometime ago I set in Mail the default font to Arial, and the default font Size to 18, so when I write a new email these are my default font and size. But I could not set the font Color. How do I do this?

    Sounds like you have the Preferences toolbar closed on another selection.
    Go to Mail > Preferences and at the top right of the Preferences window is a clear pill shaped button.
    Selecting this button opens/closes the complete Preferences toolbar.

  • Setting Font/Color for ProgressMonitor

    Hi All,
    I am using ProgressMonitor something like this.
    pbar.setNote("Loading:"+f[index].getName()+ "  " +"with Operation of " + counter + "% complete");Where pbar is an instance of ProgressMonitor.Now we can see that setNote method inside ProgressMonitor String as an argument.I want to set the font and foreground color for the text inside.Any idea how to do that??
    Any help appreciated.
    Thanks in advance.
    regards,
    Viswanadh
    Edited by: TechnicalGuy7 on Apr 24, 2009 3:42 AM

    If the progress bar had a method to set a label, instead of just set text, then you could set that label with any font and colors that you wanted...
    If you really needed to set the font color, you would need to call setUI on the progress bar, and provide you own ProgressBarUI class.
    You could start with one of the UI classes provided, like BasicProgressBarUI and extend it and modify it as you wish.
    But this is really advanced...

  • Setting font colors

    Is there a way to set the font color so that it isn't just white or whatever the default terminal font color is. I know there is a Font class, but I don't really understand how that works, whether I do Font.color and it will change the default changes or what. Can somebody direct me to more information that I can read up on, or if they know themselves. Thank you.

    I don't think fonts apply to terminals. They apply to GUIs, documents, and similar things that support different font types. I doubt there is a way using pure Java to change the color of text in a terminal, since that sounds like something that is OS specific.

  • Tab set font color

    I just downloaded the fix pack and have noticed that I am still unable to change the tab set tab font color.  Am I doing anything wrong?'
    Thanks,
    DD

    I believe what Purnima was speaking of was the Tab Background color properties.
    However, I believe there is an issue with the Label Over Color and Label Selected Color mapping properties of the Tab Set.
    Thanks.

  • Setting Font Color [CS3][JS]

    Hello,
    I am looking for a way to set the color of a piece of text that I'm inserting on the page.  I have found information about how to use a swatch color to do it, but I can't find anything about setting the color based on CMYK values without having to create a swatch first.  Likely I just don't know what properties/methods I'm searching for.
    I'm using insertion points to control the location of my text in the frame.  My code looks like this:
    r = app.activeWindow.activeSpread.groups.item('Group-1').textFrames.item('Text1');
    ip = r.insertionPoints.item(0);
    ip.appliedFont = 'ARIAL';
    ip.fillTint = 70;
    ip.tracking = +100;
    //ip.colorSettings.colorSpace [CMYK] :: Process [C=100, M=0, Y=0, K=0]  -- Not sure if this should be one line or two, and no clue how to write it - obviously.
    //ip.fillColor = 'Blue';
    ip.contents = 'This is the text that should appear process cyan based on the CMYK settings.';
    So as you can see, right now I can use a swatch, but I need to loop this script over many files and I don't really want the swatch created in all those files.
    Any help is appreciated.
    Thanks,
    Dave

    You can't directly set the fill or stroke to an arbitrary color specification — it has to be a color, swatch,  a mixed ink, a tint, or a gradient. When you apply a color using the Colors panel, in the user interface, InDesign creates a color object, even though the color object does not appear in the Swatches panel. These colors appear as unnamed colors to scripting, but they're still color objects.
    To apply a color via InDesign scripting, you must use a color or swatch object.

  • APEX 4 Interactive Report set font color of negative values to red

    I have an interactive report with several columns containing numerical values. If the value is negative, I want the font color to be red. Can someone help me with this process please.
    Application Express 4.1.1.00.23
    Thanks!
    Chris

    Hi,
    Use build in highlight
    http://docs.oracle.com/cd/E23903_01/doc/doc.41/e21674/ir_using.htm#sthref1343
    Then save report default layout
    http://docs.oracle.com/cd/E23903_01/doc/doc.41/e21674/ir_using.htm#CHDDDBCG
    Regards,
    Jari
    My Blog: http://dbswh.webhop.net/dbswh/f?p=BLOG:HOME:0
    Twitter: http://www.twitter.com/jariolai

  • How to set Font characteristics on JTEXTPane ?

    Hello,
    For 5 days, I'm looking for a way to set defaults to a text in a JTextPane. I tried many things, but I always failed.
    Here is what I want exactly to do :
    Before to display a text in a JTextPane, I want all the text to be in a particular font, with a particular size and various attributes (bold, italic, etc..).
    So before I make it visible I does the following (certainly it's wrong) :
    void InitialLoad()
            try
         in = new FileInputStream(file);
            //Create the text pane and configure it
            rtf.read(in, lpd, 0);
            TextPane.setDocument(lpd);
        catch (Exception ex)   {System.out.println("Errorr"); };
         TextPane.selectAll();
         TextPane.setCaretPosition( 1);
          String fontName=   "Arial";  
          Action FontFamily = new StyledEditorKit.FontFamilyAction(fontName, fontName);
          FontFamily.actionPerformed(null);
          int fontSize=   12;  // default size
          Action FontSize = new StyledEditorKit.FontSizeAction(""+fontSize, fontSize);
          FontSize.actionPerformed(null);
          Action italic = new StyledEditorKit.ItalicAction();
          italic.actionPerformed(null);   // italic is the default
           TextPane.setVisible(true);
    }When I do this, the text display correctly, but not with the Defaults I was expecting.
    Of course, I have implemented listener classes : UndoableEditListener, DocumentListener and UndoAction() and RedoAction()
    Any help would be very welcome. Thanks for all.

    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the [Code Formatting Tags|http://forum.java.sun.com/help.jspa?sec=formatting], so the posted code retains its original formatting.

  • Setting font and color TextItems

    This script is failing to set font, and how can I set font color?; I am new to PS Scripting:
         var originalUnit = preferences.rulerUnits
          preferences.rulerUnits = Units.INCHES
         var docRef = app.documents.add( 11, 17, 300, "Test", NewDocumentMode.CMYK)
        MyLayer = docRef.artLayers.add()
         MyLayer.kind = LayerKind.TEXT
         var myFont = app.fonts.getByName("ArialMT");
         // Set the contents of the text layer.
         var textItemRef = MyLayer.textItem
         textItemRef.font = myFont;
         textItemRef.size = UnitValue(36, 'pt');
         textItemRef.font = '_Aviano-Regular';
         textItemRef.style = "Italic";
         textItemRef.contents = "Sample Text";
         // Restore original ruler unit setting
          app.preferences.rulerUnits = originalUnit
    Thanks

    The font needs to be the postscript name, this will give you a list of them.
    var Dlog =
    "dialog{text:'Script Interface',bounds:[100,100,500,270],"+
    "FontName:DropDownList{bounds:[30,40,370,60]},"+
    "PostScriptName:DropDownList{bounds:[30,100,370,120]},"+
    "statictext0:StaticText{bounds:[40,10,200,30] , text:'Font Name'},"+
    "statictext1:StaticText{bounds:[40,70,141,87] , text:'Postscript Name'},"+
    "button0:Button{bounds:[140,130,240,150] , text:'Ok' }}";
    win = new Window(Dlog,"Use the Postscript Name in your script.");
    var item;
    var item2;
    for (var i=0,len=app.fonts.length;i<len;i++) {
      item = win.FontName.add ('item', "" + app.fonts[i].name);
      item2 = win.PostScriptName.add ('item', "" + app.fonts[i].postScriptName);   
    win.FontName.selection = win.FontName.items[0] ;
    win.PostScriptName.selection = win.PostScriptName.items[0] ;
    win.FontName.onChange = function() {
    win.PostScriptName.selection = win.PostScriptName.items[parseInt(this.selection)] ;
    $.writeln(win.PostScriptName.items[parseInt(this.selection)]);
    win.PostScriptName.onChange = function() {
    win.FontName.selection = win.FontName.items[parseInt(this.selection)] ;
    win.center();
    win.show();
    Here is your code with colour addded...
         var originalUnit = preferences.rulerUnits
          preferences.rulerUnits = Units.INCHES
          var FillColor = new SolidColor;
        FillColor.rgb.hexValue = 'ff0000';
         var docRef = app.documents.add( 11, 17, 300, "Test", NewDocumentMode.CMYK)
        MyLayer = docRef.artLayers.add()
         MyLayer.kind = LayerKind.TEXT
         var myFont = "ArialMT";
         // Set the contents of the text layer.
         var textItemRef = MyLayer.textItem
         textItemRef.font = myFont;
         textItemRef.size = UnitValue(36, 'pt');
         textItemRef.font = myFont;
         //textItemRef.style = "Italic";
         textItemRef.fauxItalic = true;
         textItemRef.contents = "Sample Text";
         textItemRef.color = FillColor;
         // Restore original ruler unit setting
          app.preferences.rulerUnits = originalUnit

  • Unable to set "Symbol" Font family to JTextpane

    Hi,
    I am developing an editor
    I am trying to set font family to Jtextpane
    javax.swing.text.Style style = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
    StyleConstants.setFontFamily(style, "Symbol");
    textPane.setCharacterAttributes(style, false);But it is not working. Same code works for other font family names ex: "Comic Sans Ms".
    Can any one know solution to this?
    Cheers
    Somasekhar
    Edited by: SomasekharPatil on Mar 13, 2009 10:42 AM

    I checked Notepad.exe where "symbol" font family is available.
    Then I think it should work in my application also. I am using Java6.
    Hope u can help me!
    Thanks in advance..

  • Different  font colors in the same text area.

    i need to have a text area where i can setText with different colors.
    eg red if an error message, rest to be black.
    the only way to set text color i know is using setforegound color which will do the only documents, but i need to set font color per string.
    how?

    JTextPane
    StyledDocument
    MutableAttributeSet
    db

  • How do you set the font color for a specific entire row inside a JTable?

    How do you set the font color for a specific entire row inside a JTable?
    I want to change the font color for only a couple of rows inside a JTable.
    I've seen some ways to possibly do this with an individual cell.
    Clarification on changing the font color in an individual cell would be helpful too if
    there is no easy way to do this for a row.

    hai,
    Try out with this piece of code.Create your table and assign the renderer to each column in the table.
    CellColorRenderer m_CellColorRenderer = new CellColorRenderer();
    for(int i=0;i<your_JTable.getColumnCount();i++)
    your_JTable.getColumnModel().getColumn(i).setCellRenderer(m_CellColorRenderer);
    class CellColorRenderer extends JLabel implements TableCellRenderer
    CellColorRenderer()     
    setOpaque(true);     
    setHorizontalAlignment(LEFT);
    setVerticalAlignment(CENTER);
    setBackground(Color.white);
    setForeground(Color.black);
    protected void setValue(Object value)
         setText((value == null) ? "" : value.toString());
    public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected, boolean hasFocus, int row,int column)
         if(isSelected == true)
              setForeground(Color.red);
         else
              setForeground(Color.black);
         setValue(value);
         return this;
    regards,
    bala

Maybe you are looking for