The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
August 2000

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

RE: Colored text

Posted by Kishori Sharan on August 16, 2000 at 12:17 PM

Hi
Here is a simple example. You need to use JTextpane.

Thanx
Kishori

///////////// ColoredText.java/////////////
/*
* Swing Version
*/

import javax.swing.*;
import javax.swing.text.*;

import java.awt.*; //for layout managers
import java.awt.event.*; //for action and window events
import javax.swing.text.StyleConstants.* ;
import java.net.URL;
import java.io.IOException;

class myFrame extends JFrame {
public myFrame ( ) {

//Create a text pane.
JTextPane textPane = createTextPane();
JScrollPane spane = new JScrollPane(textPane);
spane.setPreferredSize(new Dimension( 200, 150));
spane.setMinimumSize(new Dimension(30, 30));


JPanel panel = new JPanel();
panel.add ( spane ) ;
Container cp = getContentPane ( );
cp.add ( panel ) ;
}
private JTextPane createTextPane() {
JTextPane textPane = new JTextPane();
String[] initString = { "Hi Girish\n",
"This is a red text\n",
"This is a blue text\n",
"This is a cyan text\n",
"Thanx\nKishori"
};

String[] initStyles = { "black", "red", "blue", "cyan", "black" };

setInitStyle ( textPane );

Document doc = textPane.getDocument( );

try {
for (int i=0; i < initString.length; i++) {
doc.insertString(doc.getLength(), initString[i], textPane.getStyle(initStyles[i]));
}
} catch (BadLocationException e) {} ;

return textPane;
}

protected void setInitStyle (JTextPane textPane) {
//Set the color constants
Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);


Style blue = textPane.addStyle("blue", def);
ColorConstants.setForeground( blue, Color.blue);

Style red = textPane.addStyle("red", def);
ColorConstants.setForeground( red, Color.red);

Style cyan = textPane.addStyle("cyan", def);
ColorConstants.setForeground( cyan, Color.cyan);

Style black = textPane.addStyle("black", def);
ColorConstants.setForeground( black, Color.black);

}
}

public class ColoredText {

public static void main(String[] args) {
JFrame frame = new myFrame ( );

frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

frame.setSize ( 400, 400 );
frame.show ( );
}
}




Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us