The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


Slates and Graphics Objects

In order to draw things on the screen, you need two objects, a Slate and a Graphics object.

  • Slate: a Slate is a window that contains a blank rectangle you can draw on. The Slate class is not part of the standard Java library; it is something I wrote for this course.
  • Graphics: the Graphics object is the object we will use to draw lines, circles, etc. It is part of the Java library, so the documentation for it is on the Sun web site.
  • The methods that pertain to Graphics objects are defined in the built-in Graphics class. The methods that pertain to Slates are defined in the Slate class, which is shown in Appendix C.

    The primary method in the Slate class is makeSlate, which does pretty much what you would expect. It creates a new window and returns a Slate object you can use to refer to the window later in the program. You can create more than one Slate in a single program.

      Slate slate = Slate.makeSlate (500, 500);

    makeSlate takes two arguments, the width and height of the screen. Because it belongs to a different class, we have to specify the name of the class using "dot notation."

    The return value gets assigned to a variable named slate. There is no conflict between the name of the class (with an upper-case "S") and the name of the variable (with a lower-case "s").

    The next method we need is getGraphics, which takes a Slate object and creates a Graphics object that can draw on it. You can think of a Graphics object as a piece of chalk.

      Graphics g = Slate.getGraphics (slate);

    Using the name g is conventional, but we could have called it anything.



    Last Update: 2011-01-24