Introduction to Java 2D Graphics


Since Java is able to run across many platforms, it provides a portable platform for graphics also. Many applications can get by just fine with simple 2D graphics.
Here is a quick introduction to doing Java2D graphics within a Java Swing application. Sun maintains online api documentation and tutorials for Swing (graphical user interfaces) as well as more specific topics such as 2D graphics.

Generally, you will make use of an existing Swing component as a starting point. This object, say a JPanel, can be extended to do your custom graphics. Keep in mind that since your component shares the screen with others, it should only do its rendering at an appropriate time. For Swing components that time is signalled when the object is requested to repaint itself on the event dispatch thread. Ultimately, the custom painting is accomplished by the object's paintComponent method. Here the object is passed a Graphics (actually this is likely to be a Graphics2D) which maintains the graphics context.

       protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            display((Graphics2D) g); // display should do the drawing
        }

Since the class Graphics or it superclass Graphics2D  , keeps track of the graphics context for a component, it provides many rendering commands as well as remembering the current color, linestyle etc. A graphics may also be obtained from a component with getGraphics()

Coordinates - default range uses device coordinates which are 0,0 at the top left corner to the device(window) width-1 in pixels by device(window) height-1 in pixels. Graphics2D is able to use transforms to customize the coordinates in user space. A translate method allows integer offsets to be set for Graphics objects.

To let layout managers know what size a component would like to be, override the component's getPreferredSize method.The exact width and height of a component can be found by calling getBounds on the component. For instance, in the display method, it is common to get the current size so the background color can be used to erase the drawing area before updating it with new information. The current color is set with setColor. Colors are defined through the Color class. There are some predefined colors (BLACK, WHITE, YELLOW, etc...) and new colors can also be defined with rgb values.
 
    public Dimension getPreferredSize() {
return new Dimension(250,200);
}
        // within display method to find current size
        Rectangle rect = getBounds();
        width = rect.width;
        height = rect.height;

        // early in display to erase the window
        graphics.setColor(clearColor);
        graphics.fillRect(0, 0, width, height);


The Graphics class defines a great many methods to draw and fill geometric primitives. Look in the method summary section of the api for methods beginning with "draw" to draw arcs, lines, rectangles, rounded rectangles, ellipses (see oval), polylines and polygons. To shade in, or fill areas, look for the similar fill methods.
Text may be drawn with drawString, drawChars or drawBytes. A specific font can be set with setFont.
Images can be rendered with drawImage. An Image is a Java class, image files must be loaded and converted to Images to use these methods. Here is some sample code to load an image from an images folder located relative to where the code is called from.
  /**
     * @param name of an image file (with extension) store in images
     * @return reference to the image from the file
     */
    private BufferedImage loadImage(String name) {
        String imgFileName = "../images/"+name;
        URL url = getClass().getResource(imgFileName);
        BufferedImage img = null;
        try {
            img =  ImageIO.read(url);
        } catch (Exception e) {
            System.err.println("Failed attempt to read image: "+imgFileName);
        }
        return img;
    }

Graphics2D extends Graphics; one way is by its use of the Shape interface to draw and fill aribitrary geometry. Through shapes, the previous set of primitives can be implemented as well as new ones. One interesting example, is the GeneralPath. A GeneralPath is able to compose more complex shapes from multiple pieces.
Using plotter-like instructions to define curves (lineTo, moveTo, curveTo etc.) complex geometry can be created and manipulated as a shape. Shapes can be rendered by a Graphics2D with draw and fill methods. Areas are Shapes which allow combinations with operations such as intersection, substraction etc.

A sample project for a Java application which allows you to interactively define polylines with mouse clicks is available as a zip file. Since Java2D is part of Java there is no need to download or link in additional libraries for this example. If you've never worked with Eclipse before, you might want to look at the guidance for creating a sample JOGL (Java OpenGL) project with Eclipse.