Download unit 4 - graphics

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
UNIT 4 - GRAPHICS
UNIT OVERVIEW








4.1 Introduction to the Graphics class
4.2 The Java Coordinate System: An Introduction
4.3 Basic Methods of the Graphics Class:Creating Rectangles,Ovals, Arcs,Lines
4.4 Using the fill method
4.5 Using Colors
4.6 Creating Polygons
4.7 drawString and Changing Fonts
4.8 Creating your own methods and calling them from the paint method
4.1 INTRODUCTION TO THE GRAPHICS CLASS
As mentioned in the previous unit, the Graphics class is a pre-made java structure
that contains many built in drawing methods. To draw in an applet examine table 4.1.
Table 4.1 Basic steps in drawing in an applet
Steps
Example
declare a Graphics variable in the variable
Graphics screen;
section
declare a paint method in the method
public void paint(Graphics screen) {
section, make sure you are sending the
instructions here;
Graphics variable to the paint method as a
}
parameter
Inside the paint method: use your variable public void paint(Graphics screen {
name in combination with all the Graphics
screen.drawRect(0,0,10,10);
methods to create your drawing.
}
EXAMPLE 4.1 A SIMPLE GRAPHICS APPLET ILLUSTRATING ALL THE BASIC STEPS ABOVE
Basic applet that displays 2 messages on the applet display
Save this program as ex41.java.
import java.awt.*;
From now on save all your
programs with the same name as
public class ex41 extends java.applet.Applet{
Graphics screen; //declaring a Graphics variable
public void init() {
} //ends init method
the name used in the program
heading line
public void paint(Graphics screen) { //we send our screen variable to the paint method
screen.drawString("Welcome to unit4",50,50);
screen.drawString("Now You will start programming",50,100);
} //ends paint method
} //ends example41
WEB PAGE CODE FOR EXAMPLE4.1
<html>
<applet code="ex41.class" height=400 width=400>
</applet>
</html>
4.2 THE JAVA COORDINATE SYSTEM: AN INTRODUCTION
The java coordinate system is shown below (the coordinates of the dots are estimated).
Each point corresponds to a pixel unit. This is a term used to define distances on a
display. You will get the feel for a pixel distance on your display as you play with the
numbers in this unit.
X
0,0 starts
here and
increases in
the x and y
axis
250,20
the numbers are
written as <x,y>
The outer limits
of your x and y
axis depend on
your display
Y
20,200
300,250
Section 4.2 Mastery Questions:
1.If the square below represented a java applet with a size of 500,500, draw in the
estimated location of the following points:
a) 50,50
b) 400,10
c) 20,300
d) 250,250
e) 400,350
4.3 BASIC METHODS OF THE GRAPHICS CLASS:CREATING LINES,
RECTANGLES, OVALS, ARCS
CALLING METHODS FROM THE GRAPHICS CLASS:
Example
name of Graphics variable
the special graphics
method used
screen.drawLine(50,50,100,100); //this would draw a line.
You just have to know what parameters to send to the method and it will work. All of
the parameters must be whole numbers. If they are larger or smaller than the applet size
then that part simply will not show on the display.
Now we will go through each of the basic methods and assume that the Graphics
variable name in your program is screen. REMEMBER EACH OF THESE
COMMANDS GO INSIDE THE PAINT METHOD, THAT IS WHERE THE
DRAWING IS DONE. There is a complete example at the end of this section with all the
basic shapes.
LINES:
General Structure
screen.drawLine(starting x pixel,starting y pixel, ending x pixel, ending y pixel);
Example
screen.drawLine(10,30,100,50);
This would draw a line from coordinate 10,30 to coordinate 100,50
This translates into: the starting point on the line is 10 pixels across and 30 pixels down
the ending point on the line is 100 pixels across and 50 pixels down
<10,30>
<100,50>
RECTANGLES:
General Structure
screen.drawRect(upper left x pixel, upper left y pixel, width,height)
screen.drawRoundRect(x,y,width,height,corner width,corner height);
Example
screen.drawRect(50,20,90,120);
screen.drawRoundRect(100,20,90,120,10,5);
Same as the other
rectangle except the
corners are rounded.
The larger the corner
numbers, the more
rounded the corners
are
90 pixels wide
<50,20>
is starting
point for
upper left
corner
120 pixels height
OVALS:
Ovals are draw inside a boundary defined by a rectangle. The coordinates are written
in the exact same way as the rectangle above.
Example
screen.drawOval(50,20,90,120);
90 pixels wide
<50,20>
is starting
point for
upper left
corner
120 pixels height
The outline rectangle will
be invisible, it just shows
the boundary of the oval.
That is what your numbers
in the method define
ARCS:
An arc is a segment of an oval. If you want to draw a part of a curve an arc will do
that for you.
General Structure
screen.drawArc(x,y,width,height, start_angle,degrees from start angle to draw);
The first 4 numbers define the oval that you will be drawing a section of. These numbers
are exactly as defined in the oval section. The last 2 numbers tell which section of the
oval you want to actually draw.
The following diagram shows how to determine angles:
90 degrees
180 degrees
0 degrees
270 degrees
Example
screen.drawArc(50,150,90,120,0,180);
This would draw an arc that started at 0 degrees and went 180 degrees (counterclockwise) from that point. It would draw the top half of the oval.
sweeps
180
degrees
across
starts at 0
degrees
Here is the sample code for the basic shapes we have just covered. Type it in and run
it.The order in which you draw your shapes matters. For example, if you want a solid
blue rectangle with yellow ovals on it, you must draw the blue rectangle first, then draw
the yellow ovals. This order occurs in the paint method.
EXAMPLE 4.3 BASIC SHAPES
Applet draws all the basic shapes described in this section
import java.awt.*;
public class ex43 extends java.applet.Applet {
Graphics screen;
public void init() {
}
public void paint(Graphics screen) {
screen.drawLine(10,30,100,50);
screen.drawRect(10,100,90,100);
screen.drawRoundRect(200,100,100,100,30,10);
screen.drawOval(10,250,90,120);
screen.drawArc(200,250,90,120,0,180);
}
}//ends class
WEB PAGE CODE FOR EXAMPLE 4.3
<html>
<applet code="ex43.class" height=400 width=400>
</applet>
</html>
NOTE: As you can see, the web page code is always the same, just with a different class
name, which will run the applet you want. Now that you have seen how the web page
code works, it will not be written underneath every java example. It is quite easy for you
to do that on your own now. Don’t forget, you need to type out the web page to see any
applet you have copied from this book or any applet you have made. Also, the size used
for most of the applets in this book is height=400 width=400.
Section 4.3 Mastery Questions:
1. Make the following changes to example 4.3
 Change the size of the rectangle so it’s a square with sides of 150 pixels.
 Create a sad face inside of the rectangle. Use ovals for the eyes and nose, use an arc
for the sad frown. Also use arc for eyebrows on top of the eyes
 Make the hair on top of the rectangle a series of lines that are standing straight up
from the top of the rectangle.
4.4 USING THE FILL METHOD
Another way to draw shapes is to have them solid. For example, instead of having an
outline of an oval, you may want to have the oval filled in. You may want to do that for
any kind of shape.
To fill in a shape, instead of using the drawRect , or the drawOval etc… functions,
simply replace the word draw with the word fill. Leave all the coordinates the same.
Examples
screen.fillRect(10,10,70,100);
screen.fillOval(30,50,100,10);
screen.fillArc(50,50,100,100,0,90);
Section 4.4 Mastery Questions:
1. In the program you made for section 4.3 mastery questions, fill the 2 eyes, and fill the
sad smile.(Remember, the order of drawing matters)
4.5 USING COLORS
There are some basic colors that are included with Java, and you can also make your
own colors. You must change the current color first, then draw the shapes you want. This
will ensure that your shapes are the color you desire. You can change colors as many
times as you want.
USING BASIC JAVA COLORS
General Structure
screen.setColor(Color._______);
You would put the name of the color you want in the blank line.
The basic colors which you are allowed you put on the blank line are:
black,blue,cyan,gray,darkGray,lightGray,green,magenta,orange,pink,red,white,yellow
EXAMPLE 4.5 BASIC JAVA COLORS
Applets shows what various java colors look like
import java.awt.*;
public class ex45 extends java.applet.Applet {
Graphics screen;
public void init() {}
public void paint(Graphics screen) {
screen.drawRect(50,50,50,50);
screen.setColor(Color.blue); //changes current color
screen.fillRect(100,50,50,50);
screen.setColor(Color.red);//changes color
screen.drawOval(150,50,50,50);
screen.setColor(Color.yellow);//changes color
screen.fillArc(150,100,50,50,0,180);
}
}//ends class
CREATING YOUR OWN COLORS
The general structure for creating your own colors in Java requires the following at the
beginning of your paint method for each color you want to make.
Color __________=new Color(number for red,number for green,number for blue);
In the blank spot you would put the name of your new color.
In each of the spots in the round braces, you need to put a whole number representing
how much of that particular color you want in your new color. The number can range
from 0 to 255. It is possible to create almost any color from combinations of red,green
and blue. The colors are called RGB colors. You can find RGB number combinations on
Internet web sites.
Example
To create red (although its already made) would look like this:
Color my_red=new Color(255,0,0);
To implement the color change use the following line: You only put your new color
name inside the round braces.
screen.setColor(my_red);
NOTICE, this line is slightly different from the setColor used for basic pre-made Java
colors.
Premade Colors: screen.setColor(Color.red); //this has the word Color inside the braces
Your Own Color: screen.setColor(my_red); //only the color name in the braces.
EXAMPLE 4.5B - USING YOUR OWN COLORS.
Applet shows colors that are created by the user
import java.awt.*;
public class ex45b extends java.applet.Applet {
Graphics screen;
public void init() {
}
public void paint(Graphics screen) {
Color brown=new Color(107,69,38);
Color myred=new Color(255,50,50);
Color my_yellow=new Color(255,255,150);
screen.drawRect(50,50,50,50);
screen.setColor(brown);
screen.fillRect(100,50,50,50);
screen.setColor(myred);
screen.drawOval(150,50,50,50);
screen.setColor(my_yellow);
screen.fillArc(150,100,50,50,0,180);
}
}//ends class
Section 4.5 Mastery Questions:
1.Change the colors of your eyes in the program you made in section 4.3. Also, change
the color of the smile to a color that you make up.
4.6 CREATING POLYGONS
Polygons are multisided shapes.
Table 4.6 Steps in using Polygons
Steps
declare a Polygon variable in the variable
section: Initialize it in the init method.
In the paint method, add points to the
polygon
When you are finished defining all your
points, use any of the following to actually
draw the polygon on the screen. (The
computer will connect all your dots and
close the polygons for you)
Examples
Polygon mypoly;
mypoly=new Polygon();
mypoly.addPoint(10,10);
screen.drawPolygon(mypoly);
or
screen.fillPolygon(mypoly);
EXAMPLE 4.6 POLYGONS
Applet shows a simple hexagon in the middle of the screen
import java.awt.*;
public class ex46 extends java.applet.Applet {
Graphics screen;
Polygon mypoly;
public void init() {
}
public void paint(Graphics screen) {
mypoly=new Polygon();
screen.setColor(Color.blue);
mypoly.addPoint(100,100);
mypoly.addPoint(150,50);
mypoly.addPoint(200,50);
mypoly.addPoint(250,100);
mypoly.addPoint(200,150);
mypoly.addPoint(150,150); //automatically connects this point to the first point
screen.fillPolygon(mypoly);
}
}//ends class
Section 4.6 Mastery Questions:
1.Using example 4.6 as a template, add a filled red 8 sided shape to your program
adjusted in the last sections mastery question.
4.7 DRAWSTRING AND CHANGING FONTS
The drawString method is one which you are already quite familiar with.
Example
message to be printed
x-position of
message
y-position of
message
screen.drawString(“hello, welcome to the end of unit 4!”, 100, 100);
CHANGING FONTS
It is possible to change the size and style of writing that shows on the applet
display. You should know what types of Fonts are available on your system, or else you
can just play around with the names and see if anything changes.
SIZE: this can be a whole
number, the largest and
Example
smallest size depends on
screen.setFont( new Font ("Courier", Font.BOLD,20));
your computer.
FONT_NAME: put the name of
the font you would like to try
here. Some common ones are:
TimesRoman,Serif,Courier,Arial
etc…..
STYLE: this can be either PLAIN,
BOLD, or ITALIC (all capitals)
EXAMPLE 4.7 DRAW STRING AND FONT CHANGES
Applet shows various messages in different fonts and sizes
import java.awt.*;
public class ex47 extends java.applet.Applet {
Graphics screen;
public void init() { }
public void paint(Graphics screen) {
screen.setColor(Color.blue);
screen.drawString("Almost done unit 4!", 50,100);
screen.setFont( new Font ("Courier", Font.BOLD,20));
screen.drawString("What does this look like?",50,150);
screen.setFont( new Font ("Helvetica", Font.ITALIC,20));
screen.drawString("What does this look like?",50,250);
}
}//ends class
Section 4.7 Mastery Questions
1.Add the Italicized word “stop”, in white writing to the 8 sided red shape you drew in
Mastery section 4.6.
2.Add a blue name underneath your face, in a different font than the default one for your
system (i.e. Helvetica etc..)
4.8 CREATING YOUR OWN METHODS AND CALLING THEM FROM THE PAINT
METHOD
This chapter has gone through all of the basic shapes. Along the way you created a
program and kept adding things to it. Sometimes drawing can get very complicated and
the paint method can become very large and cluttered. Therefore, at this time, you will
learn how to write your own simple methods and use them to help organize your
program. This idea will be used for picture applets and for other types of programs later
on in the book.
CREATING YOUR OWN METHOD.
General Structure
All of the bold faced items are the ones which you will fill in. The rest must be typed as
shown. Methods shouldn’t be longer than 1 screen length.
public void name(Graphics screen ) {
instructions;
instructions;
instructions;
}
TO CALL UP A METHOD FROM ANOTHER PART OF THE PROGRAM,
You need to send the Graphics variable to your new method because it needs it to
draw on. You must write it inside the round braces when you call it up, which sends the
Graphics variable to the method when it is called.
Example
Here is a method that will draw a small
house. We indicate that the house method is
public void house(Graphics screen) {
expecting a Graphics variable by putting the
screen.drawRect(100,100,50,50);
words Graphics screen in the round braces.
screen.drawLine(100,100,125,50);
screen.drawLine(125,50,150,100);
} //ends the house method
public void paint(Graphics screen) {
house(screen);
}//ends paint
To actually show the house
on the screen, we must call up
or activate the house method
from inside the paint method.
We are sending the Graphics variable screen to the
house method because it is expecting it. It needs
the screen to draw on.
For more information on methods, read the Methods Interlude unit.
ADVANTAGES OF USING METHODS
Here’s the advantage of what methods can do to organize your program. Imagine
drawing a scene of a house with a garage with a car in it. If you had to type all your code
inside the paint method, it would become huge! Also if there was a problem, you would
have to hunt through all the code to try to isolate which part draw what.
Here is what the paint method of an organized program might look like:
public void paint(Graphics screen) {
houseframe(screen);
windows(screen);
chimney(screen);
garage(screen);
carbody(screen);
carwheels(screen);
}//end paint method
Can you see how much easier it is to tell what the program is doing. Of course you
will still have to type all the drawing code, but it will be much easier to fix if there are
problems and someone else can help you much easier also.
EXAMPLE 4.8 USING METHODS IN A PROGRAM
Applet draws a simple house with a chimney, showing the use of methods
import java.awt.*;
public class ex48 extends java.applet.Applet {
Graphics screen;
public void init() { }
you are sending screen to
public void paint(Graphics screen) {
house so it can draw to it
house(screen);
chimney(screen);
}
if you draw anything after this
the color will be red, because
public void house(Graphics screen) {
the last setColor which was in
screen.setColor(Color.blue);
chimney was red
screen.drawRect(100,100,50,50);
screen.drawLine(100,100,125,50);
screen.drawLine(125,50,150,100);
} //ends the house method
public void chimney(Graphics screen) {
screen.setColor(Color.red);
screen.drawRect(100,50,15,50);
}//ends the chimney method
}//ends class
Section 4.8 Mastery Questions
1.Why do you need to include the Graphics variable in the method calls described above
i.e. house(screen); ?
2.What are some advantages of using methods in programming?
3.As a general rule of thumb what is the maximum length that a method should be?
4.Add a method to the example 4.8 program to make some windows on the house. Add
another method to add a door to the house.
UNIT EXERCISES
1.Fill in the blanks
a)______________________ help organize your program, making it easier to fix.
b)The ________________ variable is what java needs to draw on.
c)The last 2 numbers in the drawRect method describe the _______________ and
__________ of the rectangle.
d)The last 2 numbers in a drawArc method describe the __________________ and
____________ of the arc.
e) _______________________ are always closed shapes even if the last and first point
aren’t the same.
2.Programming Projects
a)Create a scene using all of the shapes and ideas which were presented to you in this
unit. Make sure you use methods to organize your program.