How can I do that ?

Hi ! is it possible to change the color of a charactere only on a JTextField ? For resume, i want text with letters in Black, and others in Grey, but in the same JTextField.I know setForeground(), but it is not what i want ...Thanks in advance !
[280 byte] By [under31] at [2007-9-26 1:15:42]
# 1

You can use an AttributedString and its AttributedCharacterIterator.

Here's an example from "Java 2D Graphics" by Jonathan Knudsen:

import java.awt.*;

import java.awt.font.TextAttribute;

import java.text.*;

public class IteratorTest {

public static void main(String[] args) {

Frame f = new ApplicationFrame("IteratorTest") {

public void paint(Graphics g) {

Graphics2D g2 = (Graphics2D)g;

String s = "a big surprise";

Dimension d = getSize();

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

Font serifFont = new Font("Serif", Font.PLAIN, 48);

Font sansSerifFont = new Font("Monospaced", Font.PLAIN, 48);

AttributedString as = new AttributedString(s);

as.addAttribute(TextAttribute.FONT, serifFont);

as.addAttribute(TextAttribute.FONT, sansSerifFont, 2, 5);

as.addAttribute(TextAttribute.FOREGROUND, Color.red, 2, 5);

g2.drawString(as.getIterator(), 40, 80);

}

};

f.setVisible(true);

}

}

Here is ApplicationFrame:

import java.awt.*

import java.awt.event.*;

public class ApplicationFrame extends Frame {

public ApplicationFrame() {

this("ApplicationFrame v1.0");

}

public ApplicationFrame(String title) {

super(title);

createUI();

}

protected void createUI() {

setSize(600, 400);

center();

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent we) {

dispose();

System.exit(0);

}

});

}

public void center() {

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

Dimension frameSize = getSize();

int x = (screenSize.width - frameSize.width) / 2;

int y = (screenSize.height - frameSize.height) / 2;

setLocation(x, y);

}

}

Please excuse any typos, but this does exactly what you describe. Good luck.

It's a good book, by the way (O'Reilly).

-Erik

erikweber at 2007-6-29 0:42:30 > top of Java-index,Archived Forums,Java Programming...
# 2
mmmh there's a problem ; this is AttributedString Class, and I can't put it into a JTextField ...I really need help !
under31 at 2007-6-29 0:42:30 > top of Java-index,Archived Forums,Java Programming...
# 3
No, you can't do that with a JTextField. If you use a JTextPane you can do it, but the code is quite complicated, as you can see.
DrClap at 2007-6-29 0:42:30 > top of Java-index,Archived Forums,Java Programming...
# 4
Are you sure? I remerber i seen a chat made in Java, where users can write with many colors ...
under31 at 2007-6-29 0:42:30 > top of Java-index,Archived Forums,Java Programming...