Java Swing Tutorial - Java TexturePaint(BufferedImage txtr, Rectangle2D anchor) Constructor








Syntax

TexturePaint(BufferedImage txtr, Rectangle2D anchor) constructor from TexturePaint has the following syntax.

public TexturePaint(BufferedImage txtr,    Rectangle2D anchor)

Example

In the following code shows how to use TexturePaint.TexturePaint(BufferedImage txtr, Rectangle2D anchor) constructor.

/*  w  w w .  ja v  a2s . com*/
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.TexturePaint;
import java.awt.image.BufferedImage;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    JFrame jf = new JFrame("Demo");
    Container cp = jf.getContentPane();
    MyCanvas tl = new MyCanvas();
    cp.add(tl);
    jf.setSize(300, 200);
    jf.setVisible(true);
  }
}

class MyCanvas extends JComponent {

  public void paint(Graphics g) {
    BufferedImage bim; 

    TexturePaint tp;

    String mesg = "www.java2s.com";

    Font myFont = new Font("Lucida Regular", Font.BOLD, 72);

    Color[] colors = {
      Color.red, Color.blue, Color.yellow,
    };

      int width = 8, height = 8;
      bim = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
      Graphics2D g2 = bim.createGraphics();
      for (int i=0; i<width; i++) {
        g2.setPaint(colors[(i/2)%colors.length]);
        g2.drawLine(0, i, i, 0);
        g2.drawLine(width-i, height, width, height-i);
      }
      Rectangle r = new Rectangle(0, 0, bim.getWidth(), bim.getHeight());
      tp = new TexturePaint(bim, r);

      Graphics2D g2d = (Graphics2D)g;
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
      g2d.setPaint(tp);
      g2d.setFont(myFont);
      g2d.drawString(mesg, 20, 100);
    }
}