Change text color with TextAttribute in Java
Description
The following code shows how to change text color with TextAttribute.
Example
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.font.TextAttribute;
import java.util.Hashtable;
/*from w w w .j av a 2s.c o m*/
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyCanvas extends JComponent {
public void paint(Graphics g) {
Hashtable<TextAttribute, Object> map = new Hashtable<TextAttribute, Object>();
Font font = new Font(Font.SERIF, Font.PLAIN, 24);
/* This colour applies just to the font, not other rendering */
map.put(TextAttribute.FOREGROUND, Color.BLUE);
font = font.deriveFont(map);
g.setFont(font);
g.drawString("java2s.com", 45, 150);
}
}
public class Main {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 450, 450);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »