This Graphics2D
class extends the Graphics
class to provide more sophisticated control over geometry, coordinate
transformations, color management, and text layout. This is the fundamental
class for rendering 2-dimensional shapes, text and images on the Java(tm)
platform.
One of the shortfalls of the Graphics class is its inability to adjust line thickness. This functionality is supported in the Graphics2D class.
To access the power of the Graphics2D class, you must perform a type cast of the Graphics object to a Graphics2D object (see below).
import java.awt.*; import java.applet.*; public class Program extends Applet { public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; } }
Then you can access any of the Graphics2D methods.
For example, to adjust the line thickness of any drawn objects, you can use the setStroke() method within the Graphics2D class. In order to adjust the default stroke for any objects, you need to create a new BasicStroke object and then pass the object using the setStroke() method (see below).
import java.awt.*; import java.applet.*; public class Program extends Applet { public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; BasicStroke s = new BasicStroke(5.0f); //This sets line thickness for the stroke to 5 pixels g2.setStroke(s); g2.drawLine(50,50,150,150); } }
In addition to adjusting line thickness, you can also create dashed or dotted lines.
There are many other methods available within the Graphics2D class that greatly enhance the graphics capabilities of Java. A few enhancements are the ability to fill objects with gradient fills and transform objects.