Java #07 – Drawing a Picture

Java #07 – Drawing a Picture


The DrawingPanel class used in
this video can be downloaded from
java dot martincarlisle dot com. Most modern programs use a
graphical user interface, rather than doing console I/O as with
System.out.println. In the class DrawingPicture, we
create a small picture of a yellow face. We start by creating a DrawingPanel
object. Most Java classes have JavaDoc
documentation that can be viewed in a browser. This DrawingPanel class has
JavaDoc documentation that can be downloaded along with the
source code. Looking at the documentation for the
constructor, we see that it requires two
parameters, for the width and height of the window. We’ll pick 300 by 300 for the size of
this window. Next, we get the graphics object from
the drawing panel. Graphics is a standard Java class
that supports two dimensional drawing. You can think of this as painting on
a canvas in layers. The order is important. We’ll first draw the yellow background,
then add the eyes and mouth. If we did it in the reverse order, the background would cover over
the eyes and mouth. The coordinate system for Java has
zero, zero in the upper left corner, and 299, 299 in the lower right corner, which may seem upside down vertically. This drawing panel shows you on the
bottom the coordinates of the mouse. We first set the drawing color to yellow, then draw a circle (a special case
of an oval) in the middle of the screen. The four parameters represent the
upper left corner and width and height of the bounding
box in which the circle is inscribed. We then set the color to black, and
draw two rectangles for the eyes. The parameters represent the upper
left corner, then the width and the height. Next we draw another oval
for the mouth. Finally, we copy the graphics to
the screen. This particular drawing panel class
is double-buffered. That is, the screen is not updated
until the copyGraphicsToScreen
method is called. This allows for smoother animations
and reduced flicker.

Only registered users can comment.

  1. How can I include the DrawingPanel.java file? Thats my Source:

    import java.awt.*;
    public class Main {
    public static void main(String[] args) {
    DrawingPanel panel = new DrawingPanel(600,600);
    Graphics g = panel.getGraphica();
    g.setColor(Color.GREEN);
    g.fillOval(25,25,250,250);
    g.setColor(Color.BLACK);
    g.fillRect(100, 75, 20, 80);
    g.fillRect(175, 75, 20, 80);
    g.fillOval(75, 175, 150, 50);
    panel.copyGraphicsToScreen();

    }

    }

Leave a Reply

Your email address will not be published. Required fields are marked *