about the text displayed onto any component

when I am using setForeground() method it changes color of all the previously appended text. I would like to display text in different colors simultenously can any body suggest me how can I do it. if no then please give me the reason.

If you have any answer please mail me at

dubey_dharmendra@mantramail.com

Thanks,

[349 byte] By [dubey_dharmendra] at [2007-9-26 2:13:06]
# 1
Must implement the StyledDocument interface (swing).
Eric.Vautier at 2007-6-29 9:07:10 > top of Java-index,Archived Forums,Java Programming...
# 2

Hi,

Here's an example which displays text in different colors onto a JEditorPane and a JTextPane.

import javax.swing.*;

import javax.swing.text.*;

import java.awt.*;

import java.awt.event.*;

public class ColorDemo extends JFrame {

public ColorDemo() {

super("ColorDemo");

// coloured JEditorPane

JEditorPane editorPane = new JEditorPane("text/html",

"<FONT color=red> This </FONT>"+

"<FONT color=blue> is </FONT>"+

"<FONT color=green> a </FONT>"+

"<B> JEditorPane </B>");

editorPane.setPreferredSize(new Dimension(250, 150));

// coloured JTextPane

JTextPane textPane = new JTextPane();

textPane.setPreferredSize(new Dimension(250, 150));

Document doc = textPane.getDocument();

Style def = StyleContext.getDefaultStyleContext().

getStyle(StyleContext.DEFAULT_STYLE);

try {

StyleConstants.setForeground(def, Color.blue);

doc.insertString (0, "This ", def);

StyleConstants.setForeground(def, Color.red);

doc.insertString (5, "is ", def);

StyleConstants.setForeground(def, Color.green);

doc.insertString (8, "a ", def);

StyleConstants.setBold(def, true);

StyleConstants.setForeground(def, Color.black);

doc.insertString (10, "JTextPane", def);

} catch (Exception e) {}

JPanel contentPane = new JPanel();

contentPane.add(textPane);

contentPane.add(editorPane);

setContentPane(contentPane);

}

public static void main(String[] args) {

JFrame frame = new ColorDemo();

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);

}

});

frame.pack();

frame.setVisible(true);

}

}

Hope this helps,

Kurt.

leukbr at 2007-6-29 9:07:10 > top of Java-index,Archived Forums,Java Programming...