This code generate a colored text in JTextPane like this image

<br />
<p>import javax.swing.*;</p><br />
<p>import javax.swing.text.*;</p><br />
<p>import java.awt.Color;</p><br />
<p>public class ColorPane extends JTextPane {</p><br />
<p>public void appendNaive(Color c, String s) { // naive implementation</p><br />
<p>// bad: instiantiates a new AttributeSet object on each call</p><br />
<p>SimpleAttributeSet aset = new SimpleAttributeSet();</p><br />
<p>StyleConstants.setForeground(aset, c);</p><br />
<p>int len = getText().length();</p><br />
<p>setCaretPosition(len); // place caret at the end (with no selection)</p><br />
<p>setCharacterAttributes(aset, false);</p><br />
<p>replaceSelection(s); // there is no selection, so inserts at caret</p><br />
<p>}</p><br />
<p>public void append(Color c, String s) { // better implementation--uses StyleContext</p><br />
<p>StyleContext sc = StyleContext.getDefaultStyleContext();</p><br />
<p>AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY,</p><br />
<p>StyleConstants.Foreground, c);</p><br />
<p>int len = getDocument().getLength(); // same value as getText().length();</p><br />
<p>setCaretPosition(len); // place caret at the end (with no selection)</p><br />
<p>setCharacterAttributes(aset, false);</p><br />
<p>replaceSelection(s); // there is no selection, so inserts at caret</p><br />
<p>}</p><br />
<p>public static void main(String argv[]) {</p><br />
<p>ColorPane pane = new ColorPane();</p><br />
<p>for (int n=1; n < = 400; n+=1) {</p><br />
</p><p>if (isPrime(n)) {</p><br />
<p>pane.append(Color.red, String.valueOf(n)+' ');</p><br />
<p>} else if (isPerfectSquare(n)) {</p><br />
<p>pane.append(Color.blue, String.valueOf(n)+' ');</p><br />
<p>} else {</p><br />
<p>pane.append(Color.black, String.valueOf(n)+' ');</p><br />
<p>}</p><br />
<p>}</p><br />
<p>JFrame f = new JFrame("ColorPane example");</p><br />
<p>f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);</p><br />
<p>f.setContentPane(new JScrollPane(pane));</p><br />
<p>f.setSize(600, 400);</p><br />
<p>f.setVisible(true);</p><br />
<p>}</p><br />
<p>public static boolean isPrime(int n) {</p><br />
<p>if (n < 2) return false;</p><br />
</p><p>double max = Math.sqrt(n);</p><br />
<p>for (int j=2; j < = max; j+=1)</p><br />
</p><p>if (n % j == 0) return false; // j is a factor</p><br />
<p>return true;</p><br />
<p>}</p><br />
<p>public static boolean isPerfectSquare(int n) {</p><br />
<p>int j = 1;</p><br />
<p>while (j*j < n &amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp; j*j > 0)</p><br />
<p>j += 1;</p><br />
<p>return (j*j == n);</p><br />
<p>}</p><br />
<p>}</p><br />
<p>





Visitor from Russia
very nice
EADOKING BLOG
Visitor from Russia
very nice
EADOKING BLOG
Trasnslation is
to all friends and people who visit my blog
you are welcome
Trasnslation is
to all friends and people who visit my blog
you are welcome
Кому интересно пишите
Кому интересно пишите