String gradient paint in Java

Description

The following code shows how to string gradient paint.

Example


import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
//  w w  w .j  a va  2  s. c  om
import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2D = (Graphics2D) g;
    int w = getSize().width;
    int h = getSize().height;
    Font font = new Font("Dialog", Font.BOLD, 40);
    FontMetrics fontMetrics  = getFontMetrics(font);;
    g2D.setFont(font);
    GradientPaint gp = new GradientPaint(
                            30.0f, 50.0f,
                            Color.blue,
                            fontMetrics.stringWidth("Hello!"),
                            fontMetrics.getHeight(),
                            Color.red);             
    g2D.setPaint(gp);
    g2D.drawString("java2s.com", 20,200);     
  }
}

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.

String gradient paint in Java




















Home »
  Java Tutorial »
    Graphics »




Animation
BufferedImage
Color
Font
Gradient
Graphics Settings
Image
Mouse Draw
Print
Shape
Text
Transform