Java graphics programming
You can display various graphics including lines, rectangles, ovals, and images in Java programs.
This tutorial focuses on:
- The Canvas class
- Displaying graphics on a component
- Drawing lines
- Drawing rectangles
- Drawing ovals
- Drawing images
The Canvas class
The first thing you will need is the Canvas class. This class is used to create an area in a frame to be used for displaying graphics.
NOTE: All the classes you will need to display graphics (as well as frames) are located in the java.awt package.
Canvas class methods:
- void setSize(width, height) - Sets the size of the canvas
- void setBackground(Color c) - Sets the background color of the canvas
- void setForeground(Color c) - Sets the text color of the canvas
Displaying graphics on a component
Now that you have a Canvas (an area to display graphics on) how do you actually display those graphics? With the paint() method of the Frame class.
The paint() method takes one attribute - an instance of the Graphics class. The Graphics class contain methods which are used for displaying graphics. The Graphics class lets a component draw on itself.
Drawing lines
To draw lines, the drawLine() method of the Graphics class is used. This method takes four numeric attributes - the first two indicating the x/y starting point of the line, the last two indicating the x/y ending point of the line.
Drawing rectangles
To draw rectangles, the drawRect() method is used. This method takes four numeric attributes - the first two indicating the x/y starting point of the rectangle, the last two indicating the width and height of the rectangle.
Filling a rectangle
By default a rectangle will have no color on the inside (it will just look like a box). You can use the fillRect() method to fill a rectangle. The fillRect() method has four numeric attributes indicating the x/y starting position to begin filling and the height and width. Set these values the same as you did for the drawRect() method to properly fill the rectangle.
Something's missing...
The rectangle is filled, but we didn't set a color for it! To do this, we will use the setColor() method.
Drawing ovals
To draw ovals, the drawOval() method is used. This method takes four numeric attributes - the first two indicating the x/y starting point of the oval, the last two indicating the width and height of the oval. Fill an oval with the fillOval() method which also takes four numeric attributes indicating the starting position to begin filling and the height and width. Set these values the same as you did for the drawOval() method to properly fill the oval.
Displaying images
To display images, the Image class is used together with the Toolkit class. Use these classes to get the image to display. Use the drawImage() method to display the image.
What it will look like:
