Java Graphics2D Class: Uses & Features

Instructor: Martin Gibbs

Martin has 16 years experience in Human Resources Information Systems and has a PhD in Information Technology Management. He is an adjunct professor of computer science and computer programming.

We are long past the days of 8-bit graphics. In this lesson you will learn how to implement advanced graphic features of the Java Graphics2D class. Working code examples are provided.

Java Graphics

When 8-bit graphics just won't cut it, you can take advantage of more advanced graphics design of your applications.

The Java AWT (Advanced Window Toolkit) is an API (Application Programming Interface) that provides the horsepower for our GUI (Graphical User Interface) development. You know you are studying computer science when a sentence is more acronyms than words!

We also will make use of the Java JFrame. Think of this as a palette to add graphics, form elements, etc., into a window on the screen. It is like a Windows application with only a gray screen with an x in the corner.

Java provides a Graphics class as part of AWT, and the Graphics2D class inherits all properties from Graphics (it is a child class), plus it has its own methods and features. With the Java Graphics2D class, you have control over high-quality, two-dimensional graphics. This includes lines, shapes, images, fonts, etc.

Methods

Some of the cool things that the Graphics2D class can do include:

  • Transform drawing objects: rotate, scale and shear
  • Create a pen-drawing effect on shapes and set the stroke (pattern start- and end-point attributes, and point size)
  • Fill (color, gradient, pattern) of shapes
  • Overlap shapes (or even check to see if shapes overlap: this is important in gaming when you want to ensure objects don't collide)
  • Fonts

In your Java compiler, you can right-click on the Graphics2D class name and select the Java documentation for this class (actually for any class or Java reserved word!). Inside you will find a wealth of information regarding this class.

The following is from NetBeans IDE:


Javadocs for Graphics2D


Examples

We mentioned the Advanced Window Toolkit (AWT), and the Java JFrame. Each program you create will need to import this API:

//import the whole API:
import java.awt.*;
import javax.swing.*;

As we learn these concepts, we will import the whole API. However, as programs grow in size and complexity, you can import each individual class from the API as needed. For example, to import each specific component for a given program, the following will work:

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import java.awt.*;

Lines

As an example of the features of the Graphics2D class, let's draw a line. Sure, a line on the screen doesn't sound too exciting, but you can't build the next-generation first-person-shooter without knowing the building blocks of graphics!

First, be sure to create a Java program using a compiler of your choice (this lesson uses the NetBeans IDE). Next, import the AWT toolkit and the JFrame. (we'll just import the whole thing). Next, create a new program with a class name of Java2DExamples, creating the constructor to setup the frame.

public class Java2DExamples extends JFrame {
  //constructor name matches class name!
  public Java2DExamples() {
   super('Let's Draw a Line');
   setSize(300, 300);
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   setLocationRelativeTo(null);
  }

Next, we will add the code that sets up the line. This method is still within the main class (Java2DExamples):

  void drawLines(Graphics g) {
  //create new Graphics2D instance using Graphics parent
  Graphics2D g2 = (Graphics2D) g;
  //set color
  g2.setColor(Color.GREEN);
  //set thickness
  Stroke stroke = new BasicStroke(2f);
  //draw the line, start x/y coords; end x/y coords;
  //it's a Double because you can be super-precise
  g2.setColor(Color.GREEN);
  //set the thickness... increase the number and see what happens, e.g. 6f
  g2.setStroke(new BasicStroke(4f));
  //draw the line
  g2.draw(new Line2D.Double(59.2d, 99.8d, 219.1d, 99.8d));
}

Next we need to use the paint() method from the JFrame class to draw our enhanced line:

public void paint(Graphics g) {
  super.paint(g);
  drawLines(g);
}

Finally, update the main method in the program to execute the code we've been working on. The final curly bracket closes out the Java2DExamples main class:

public static void main(String[] args) {
  SwingUtilities.invokeLater(new Runnable() {
   @Override
  public void run() {
     new Java2DExamples().setVisible(true);
   }
 });
}
}

When this code is run, the shape is as follows:


Java Graphics2DLine


To unlock this lesson you must be a Study.com Member.
Create your account

Register for a free trial

Are you a student or a teacher?
I am a teacher

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back

Earning College Credit

Did you know… We have over 160 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Transferring credit to the school of your choice

Not sure what college you want to attend yet? Study.com has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

Create an account to start this course today
Try it free for 5 days!
Create An Account
Support