Java AWT Graphics2D draw styled String

Description

Java AWT Graphics2D draw styled String

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.RenderingHints;
import java.awt.font.TextAttribute;
import java.text.AttributedString;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {
  Random rnd = new Random();

  @Override//from w  ww . jav a  2  s.co m
  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g;
    g2d.setBackground(Color.WHITE);
    g2d.clearRect(0, 0, getParent().getWidth(), getParent().getHeight());
    // antialising
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    AttributedString attrStr = new AttributedString("www.demo2s.com");

    Font serif = new Font(Font.SERIF, Font.PLAIN, 50);
    attrStr.addAttribute(TextAttribute.FONT, serif, 0, 4);
    
    g2d.drawString(attrStr.getIterator(), 50, 100);
  }

  public static void main(String[] args) {
    // create frame for Main
    JFrame frame = new JFrame("java2s.com");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Main Main = new Main();
    frame.add(Main);
    frame.setSize(300, 210);
    frame.setVisible(true);
  }
}



PreviousNext

Related