How do I draw a string in Java 2D?

The code snippet below show you how to draw a string using Graphics2D. The drawString() method accept the string to be drawn and their x and y coordinate. Here you can also see how to set the antialiasing mode using the setRenderingHint() method.

Run the snippet and you’ll see the following screen:

Draw String Demo

How do I draw a vertical text in Java 2D?

To draw a text / string vertically we need to do a transform on the Graphics2D object. First, create an instance of AffineTransform and set the rotation using the setToRotation() method. And then pass this transform object into g2.setTransform() method.

Run the snippet and you’ll see the following screen:

Draw Vertical Text Demo

How do I create a gradient paint in Java 2D?

To change the color of a graphics shape we can use the setPaint() method. For a simple coloring we can pass the color object into this method, such as Color.RED or Color.GREE.

If you want to paint with a gradient paint you can use the GradientPaint class. This class provides a way to fill a shape with a linear color gradient pattern. To create a gradient color pattern you can pass the following parameter to the object constructor.

  • x1: x coordinate of the first specified point in user space
  • y1: y coordinate of the first specified point in user space
  • color1: color at the first specified point
  • x2: x coordinate of the second specified point in user space
  • y2: y coordinate of the second specified point in user space
  • color2: color at the second specified point


This code snippet produce the following output:

Gradient Paint Demo