Hey guys I've got a JText field set up and i append strings to the JTextField but im wondering how to invidually set the color of each string that i append? I've taken a look at the JLabel class and I did come up with the idea that I could just make a new JLabel and set the color and string and then paint that onto a JTextField. However this doesnt appear to work. Nothing gets display if I attempt to do it this way.

Is there a work around? I know the JTextField has its own setForegroundColor(); but this sets it for the whole text thats present.

hmmm, it would appear that it gets it source from an HTML format? Not really what I had in mind. My system is producing strings and I'd liked them to be placed on a canvas. I've attempted to add JLabels to it and, it works but doesnt look that nice. Also adding JLabels isn't that safe.

I'm not quite following you. You mentioned placing them in a JTextField, but here you mention placing them on a canvas. Which is the case? One involves styled-text within an editing component, whereas painting them on a canvas evokes an expectation of custom 2D graphics rendering. Also, the comment about JLabels not being safe is a bit unclear.

At the minute I've got a JTextField which I write Strings to (my system produces String messages which I wish to show to the user via my gui window).

Certain messages come through and at the minute they are all the same color. I wish to seperate out the different messages and make them a specfic color accordingly.

I've had a look at the JTextPane and EditorPane they both from what I understand construct themselves via a HTML markup document ? Please correct me if I'm wrong.

I read somewhere that its bad to place a label in a JTextPane / EditorPane (Will dig it out and post it)

You do not have to use HTML markup to created styled text in JTextPane. In addition to the tutorial link I posted above, perhaps these examples will help:
http://www.exampledepot.com/egs/javax.swing.text/style_HiliteWords2.html

As far as the JLabel, you're right, you don't place it in a JTextPane - but then that wasn't really the nature of the suggestion. The intent was that you could use a JLabel in place of JTextField or JTextPane in your container and use HTML markup to control the style and formatting of the displayed text.

ok I've gone down the route of making it a JTextPane, I'm lost in how to append text to the pane?

The TextSamplerDemo from Sun has some example code on adding styled text to a JTextPane. It's a bit different than working with JTextField because the text pane utilizes a styled document. Since there is a lot of clutter from other text component code in that demo, I'll paste the two relevant methods here

private JTextPane createTextPane() {
    String[] initString =
            { "This is an editable JTextPane, ",            //regular
              "another ",                                   //italic
              "styled ",                                    //bold
              "text ",                                      //small
              "component, ",                                //large
              "which supports embedded components..." + newline,//regular
              " " + newline,                                //button
              "...and embedded icons..." + newline,         //regular
              " ",                                          //icon
              newline + "JTextPane is a subclass of JEditorPane that " +
                "uses a StyledEditorKit and StyledDocument, and provides " +
                "cover methods for interacting with those objects."
             };

    String[] initStyles =
            { "regular", "italic", "bold", "small", "large",
              "regular", "button", "regular", "icon",
              "regular"
            };

    JTextPane textPane = new JTextPane();
    StyledDocument doc = textPane.getStyledDocument();
    addStylesToDocument(doc);

    try {
        for (int i=0; i < initString.length; i++) {
            doc.insertString(doc.getLength(), initString[i],
                             doc.getStyle(initStyles[i]));
        }
    } catch (BadLocationException ble) {
        System.err.println("Couldn't insert initial text into text pane.");
    }

    return textPane;
}

protected void addStylesToDocument(StyledDocument doc) {
    //Initialize some styles.
    Style def = StyleContext.getDefaultStyleContext().
                    getStyle(StyleContext.DEFAULT_STYLE);

    Style regular = doc.addStyle("regular", def);
    StyleConstants.setFontFamily(def, "SansSerif");

    Style s = doc.addStyle("italic", regular);
    StyleConstants.setItalic(s, true);

    s = doc.addStyle("bold", regular);
    StyleConstants.setBold(s, true);

    s = doc.addStyle("small", regular);
    StyleConstants.setFontSize(s, 10);

    s = doc.addStyle("large", regular);
    StyleConstants.setFontSize(s, 16);

    s = doc.addStyle("icon", regular);
    StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
    ImageIcon pigIcon = createImageIcon("images/Pig.gif",
                                        "a cute pig");
    if (pigIcon != null) {
        StyleConstants.setIcon(s, pigIcon);
    }

    s = doc.addStyle("button", regular);
    StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);
    ImageIcon soundIcon = createImageIcon("images/sound.gif",
                                          "sound icon");
    JButton button = new JButton();
    if (soundIcon != null) {
        button.setIcon(soundIcon);
    } else {
        button.setText("BEEP");
    }
    button.setCursor(Cursor.getDefaultCursor());
    button.setMargin(new Insets(0,0,0,0));
    button.setActionCommand(buttonString);
    button.addActionListener(this);
    StyleConstants.setComponent(s, button);
}

They are basically concatenating the various strings from their array to end of the document with the desired style with the insertString() method.

Hope that helps a bit.

This article has been dead for over six months. Start a new discussion instead.