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.

Change text color with TextAttribute in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer