UCL Logo

 

The template code for the simple drawing program is as follows (the fixed infrastructure code is in bold):

// Written by A.Person, 1/10/05
// This program draws a simple picture.


// Use code from the Java libraries
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


// This program will be called Drawing and needs
// to stored in a file called Drawing.java.
// To create your own program with a different name,
// change *all* the occurances of Drawing to the new
// name. Save the program to a new file named using the
// new name with .java appended.
class Drawing extends JFrame
{
  class DrawPanel extends JPanel
  { 
    //---------------------------------------------------
    // This part of the program does the actual drawing.
    public void doDrawing(Graphics g)
    {
      // You add/change the statements here to draw
      // the picture you want.
      g.drawLine(0,0,300,300);	
    }
    //---------------------------------------------------

    // This controls the drawing of the window
    // contents.
    public void paint(Graphics g)
    {
      g.setColor(Color.white);
      g.fillRect(0,0,getWidth(),getHeight());
      g.setColor(Color.black);
      doDrawing(g);
    }	

    // This part of the program makes sure that
    // the window drawing area ends up being the
    // right size. You don't need to change this.
    public Dimension getPreferredSize()
    {
      return new Dimension(WIDTH,HEIGHT);
    }
	
    // These set the size of the drawing area.
    // By default this will be 300 by 300 pixels.
    // Change the sizes to suit what you need.
    private int WIDTH = 300;
    private int HEIGHT = 300;
  }
  
  // Create a new window frame.
  public Drawing(String name)
  {
    super(name);
    setupWindow();
  } 
    
  // Tell the window object to display itself.
  public void display()
  {
    pack();
    setVisible(true);
  }
  
  private void setupWindow()
  {
    // Create the contents of the window. The top (or Center)
    // part is the drawing area. The bottom (or South) strip 
    // holds a quit button.
    DrawPanel drawing = new DrawPanel();
    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new BorderLayout());
    JButton quitButton = new JButton("Quit");
    buttonPanel.add("Center",quitButton);
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add("Center",drawing);
    getContentPane().add("South",buttonPanel);
    // The event listeners are set up here to enable the
    // program to respond to events.
    quitButton.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent evt)
      {
        quit();
      }
    });
    addWindowListener(new WindowAdapter()
    {
      public void windowClosing(WindowEvent evt)
      {
        quit();
      }
    });
  }

  // This will terminate the program when the user
  // wants to quit.
  private void quit()
  {
    System.exit(0);
  }  

  // This part of the program sets everything up
  // and displays the drawing window.
  public static void main(String[] args)
  {
    // Create the window object with the label
    // "My Drawing". Change the label text to change
    // the label.
    Drawing frame = new Drawing("My Drawing");
    frame.display();
  }
}

To run this program, type in the program code and store it into a file called Drawing.java (or if you are paying attention use copy and paste from the web page version of these exercises to avoid typing in all the code!) Compile the code using the command:

javac Drawing.java

and then run the program using:

java Drawing

A window like this should appear on the screen: Drawing Window

(Or you can use JEdit or BlueJ.)

The window contains a line drawn by the statement:

 g.drawLine(0,0,300,300);

In technical terms this means call the method drawLine for the graphics object g, specifying the end points of the line as 0,0 and 300,300. The full meaning of this will become clear in time but it should be obvious that drawLine means draw a line using the start and end points specified. The task of actually drawing the line is performed by the graphics object, without you needing to know how that actually happens. The punctuation (dot, commas and semi-colon) must be present - when you write a drawing program try leaving some of them out and see what happens!

Drawing lines works much the same way as drawing on a piece of graph paper. Notice that the diagonal line slopes from top to bottom, left to right. The co-ordinate of the top left of the window is (0,0), while the co-ordinate at the bottom right is (300,300). Based on this you should be able to work out how to draw a line in any position (just like drawing on graph paper, except you have to remember that (0,0) is at top left not bottom left).

This window will remain on the screen while the program is still running. To stop the program click the Quit button at the bottom of the window. Clicking the button generates an event that the program responds to and it will stop running. Alternatively, the program will stop if you click the window frame close control (providing the window manager of the operating system you are using supplies one). Programs can also be stopped by typing Ctrl-C in the terminal window, if they were started from the command line.

If you read the comment lines in the program carefully you will see the things that you can change. In particular, look for the part where it says:

// You add/change the statements here to draw
// the picture you want.

To draw something different you add or edit statements here. For example, to draw a line from bottom left to top right change the statement:

g.drawLine(0,0,300,300);

to:

g.drawLine(0,300,300,0);

Other Drawing Methods

What else can be drawn? The following is a list of some of the possibilities:

  • g.drawArc(x, y, width, height, startAngle, arcAngle). Draw an arc inside the rectangle with top left corner at (x,y) and size given by width and height.
    startAngle is the angle in degrees that specifies where the arc starts (0 is the 3 o'clock position).
    arcAngle is the angle in degrees that specifies the end of the arc, relative to startAngle.
    Don't follow this? Write a test program and experiment!!
  • g.drawOval(x,y,width,height). Draw an oval inside the rectangle with top left corner at (x,y) and size width by height.
  • g.drawRect(x,y,width,height). Draw a rectangle with top left hand corner at (x,y) and size width by height.
  • g.drawString(text, x,y). Display the text at position (x,y). The text is specified as a string in double quotes, for example:
    g.drawString("Hello",40,40).

If you want know more, visit the online Java documentation and look for class Graphics. On the local CS web this can be seen at: http://www.cs.ucl.ac.uk/teaching/java/javadoc/index.html. At first sight this documentation will appear complex and unfriendly. But don't be put off, over time you will make sense of it and find it becomes an invaluable source of information.


Last updated: September 2, 2006

Computer Science Department - University College London - Gower Street - London - WC1E 6BT - Telephone: +44 (0)20 7679 7214 - Copyright 1999-2006 UCL


 Search by Google