Skip to Content
Think Java, 2nd Edition
book

Think Java, 2nd Edition

by Allen B. Downey, Chris Mayfield
November 2019
Beginner
326 pages
6h 44m
English
O'Reilly Media, Inc.
Book available
Content preview from Think Java, 2nd Edition

Appendix C. Graphics

The Java library includes the package java.awt for drawing 2D graphics. AWT stands for Abstract Window Toolkit. We are only going to scratch the surface of graphics programming. You can read more about it in the Java tutorials.

Creating Graphics

There are several ways to create graphics in Java; the simplest way is to use java.awt.Canvas and java.awt.Graphics. A Canvas is a blank rectangular area of the screen onto which the application can draw. The Graphics class provides basic drawing methods such as drawLine, drawRect, and drawString.

Here is an example program that draws a circle by using the fillOval method:

import java.awt.Canvas;
import java.awt.Graphics;
import javax.swing.JFrame;

public class Drawing extends Canvas {
    public static void main(String[] args) {
        JFrame frame = new JFrame("My Drawing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Drawing drawing = new Drawing();
        drawing.setSize(400, 400);
        frame.add(drawing);
        frame.pack();
        frame.setVisible(true);
    }



    public void paint(Graphics g) {
        g.fillOval(100, 100, 200, 200);
    }
}

The Drawing class extends Canvas, so it has all the methods provided by Canvas, including setSize. You can read about the other methods in the documentation, which you can find by doing a web search for “Java Canvas”.

In the main method, we do the following:

  1. Create a JFrame object, which is the window that will contain the canvas.

  2. Create a Drawing object (which is the canvas), set its width and height, and add it to the ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Head First Java, 2nd Edition

Head First Java, 2nd Edition

Kathy Sierra, Bert Bates
Java in a Nutshell, 8th Edition

Java in a Nutshell, 8th Edition

Benjamin J. Evans, Jason Clark, David Flanagan
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan
The Well-Grounded Java Developer, Second Edition

The Well-Grounded Java Developer, Second Edition

Benjamin Evans, Martijn Verburg, Jason Clark

Publisher Resources

ISBN: 9781492072492Errata PageSupplemental Content