using graphics building java programs supplement 3g · 2019-01-29 · •drawoval(x, y, width,...

Post on 24-May-2020

2 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Using Graphics

Building JavaPrograms

Supplement 3G

IntroductionSo far, you have learned how to:

❑ output to the console❑ break classes/programs into static methods❑ store and use data with variables

❑ write for loops for repetitive tasks

❑ pass parameters to a method❑ return values from a method

❑ use String and Scanner objects

Now you will have a way to output to the user other than using the console.

ReviewCalling static methods from another class:

❑ Classname.methodname(actual parameters);double square = Math.pow (x, 2);

Calling (non-static) methods on an instance of a class (object):

❑ variablename.methodname(actual parameters);Scanner console = new Scanner(System.in);int userInput = console.nextInt();

Graphical ObjectsWe will need the following three objects for drawing graphics in Java:

• DrawingPanel: A window on the screen.

– Not part of Java; provided by the textbook authors.

• Graphics: A "pen" to draw shapes and lines on a

window.

• Color: Colors in which to draw shapes.

Like with String and Scanner, you will not have to write these classes on your own but will simply use them.

DrawingPanel BasicsDrawingPanel represents a window on the screen, or the canvas on which the graphics will be drawn.

Since DrawingPanel is an object type, we must use the constructor to create a new instance:

DrawingPanel name = new DrawingPanel(width, height);

The constructor takes two parameters which represent the width and height of the drawing area.

Example:DrawingPanel panel = new DrawingPanel(500,500);

Try it out/** * Program that will be used to show the basics for learning* graphics * @author Your Name */

public class LearningGraphics { /** * Declares the variables, computes the position, and prints the* results. * @param args command line arguments (not used)*/ public static void main(String[] args) {

DrawingPanel panel = new DrawingPanel(500, 500); }

}

From Moodle site, download the following files into the same folder:

DrawingPanel.java

LearningGraphics.java

Compile both and then execute:$ java LearningGraphics

• Each (x, y) position is a pixel ("picture element").

• Position (0, 0) is at the window's top-left corner.

– x increases rightward and the y increases downward.

• The rectangle from (0, 0) to (200, 100) looks like this:

(0, 0) x+

(200, 100)

y+

Coordinate System

7

Graphics BasicsGraphics represents the pen or paint that we will use to draw lines and shapes on the canvas (DrawingPanel).

Graphics is part of the Java Class Library.Since Graphics belongs to a package named java.awt(Abstract Window Toolkit), we will need to include the following import statement in our programs that use Graphics:

import java.awt.*;

Add this import statement to the top (as the first line) of LearningGraphics.java

Since we are using DrawingPanel, we will not have to construct new Graphics objects. Instead, we will use the DrawingPanel's getGraphics() method. We will access the Graphics object as follows:

Graphics g = panel.getGraphics();

Graphics methodsWe will discuss some of the Graphics methods here; you can read about all of the Graphics methods in its API.

•drawLine(x1, y1, x2, y2): draws a line between the points (x1, y1) and (x2, y2)

•drawOval(x, y, width, height): draws the outline of the largest oval that fits within the specified rectangle

•drawRect(x, y, width, height): draws the outline of the specified rectangle

•drawString(message, x, y): draws the given text with its lower-left corner at (x, y)

•fillOval(x, y, width, height): fills the largest oval that fits within the specified rectangle using the current color

•fillRect(x, y, width, height): fills the specified rectangle using the current color

•setColor(color): sets this graphics context's current color to the specified color (all subsequent graphics operations using this graphics context use this specified color)

•setFont(font): sets this graphics context's current font to the specified font (all subsequent strings drawn using this graphics context use this specified font)

9

Try it out•Let's modify LearningGraphics.java

•include two rectangles---one filled in and one outlined.

•Add the lines below to the main method of your LearningGraphicsClass (after the creation of the DrawingPanel object):

Graphics g = panel.getGraphics(); g.fillRect(100, 100, 100, 200); g.drawRect(0, 0, 100, 100);

10

Color Basics• Color represents the color that we will draw

lines and shapes on the canvas (DrawingPanel) with.

• Color is also part of the java.awt package. We will discuss some of the Color constants and methods here. You can read about all of the Color constants and methods in its API.

• In the same way that we used Math.PI for the value of pi, we can use the Color constants to access the predefined colors.

• Can use predefined Color class constants:

Color.CONSTANT_NAME

where CONSTANT_NAME is one of:

BLACK, BLUE, CYAN, DARK_GRAY, GRAY,

GREEN, LIGHT_GRAY, MAGENTA, ORANGE,

PINK, RED, WHITE, YELLOW

• Or create one using Red-Green-Blue (RGB) values of 0-255

Color name = new Color(red, green, blue);

– Example:Color brown = new Color(192, 128, 64);

Specifying Color

12

Using Color colors

13

• Pass a Color to Graphics object's setColor method

– Subsequent shapes will be drawn in the new color.

g.setColor(Color.BLACK);

g.fillRect(10,

g.drawLine(20,

30, 100, 50);

0, 10, 30);

g.setColor(Color.RED);

g.fillOval(60, 40, 40, 70);

• Pass a color to DrawingPanel's setBackground

method

– The overall window background color will change.

Color brown = new Color(192, 128, 64);

panel.setBackground(brown);

Try it out• Let's modify LearningGraphics.java

Change the background to red and add a blue circle

• Add the red lines below to the main method of your LearningGraphics class:

public static void main(String[] args) { DrawingPanel panel = new DrawingPanel(500, 500);panel.setBackground(Color.RED);

Graphics g = panel.getGraphics(); g.fillRect(100, 100, 100, 200); g.drawRect(0, 0, 100, 100);

g.setColor(Color.BLUE); g.fillOval(200, 200, 100, 100);

}

14

• To draw a colored shape with an outline, first fill it, then

draw the same shape in the outline color

// inner blue filled circle (from last slide)

g.setColor(Color.BLUE);

g.fillOval(200, 200, 100, 100);

• Add the lines below to the end of the main method of your LearningGraphicsclass:

// white outline of circle

g.setColor(Color.WHITE);

g.drawOval(200, 200, 100, 100);

15

Outlining Shapes

• The x,y,w,h expressions can use the loop counter variable:

panel.setBackground(Color.YELLOW);

g.setColor(Color.RED);

for (int i = 1; i <= 10; i++) {

// x y w h

g.fillOval(100 + 20 * i, 5 + 20 * i, 50, 50);

}

• Nested loops can be used with graphics:g.setColor(Color.BLUE);

for (int x = 1; x <= 4; x++) {

for (int y = 1; y <= 9; y++) {

g.drawString("Java", x * 40, y *

}

}

25);

Drawing with Loops

16

Add these lines to the end of the main method of your LearningGraphics class:

for (int i = 1; i <= 5; i++) {

g.setColor(Color.YELLOW);

g.fillRect(450 - 20 * i, 5 + 20 * i, 50, 50);

g.setColor(Color.BLUE);

g.drawRect(450 - 20 * i, 5 + 20 * i, 50, 50);

}

g.setColor(Color.WHITE);

for (int x = 1; x <= 4; x++) {

for (int y = 1; y <= 9; y++) {

g.drawString("Java", 500 - x * 40, 500 - y * 25);

}

}17

Try it Out

90);

10);

90);

Objects that represent arbitrary shapes

• Add points to a Polygon using its addPoint(x,y) method.

• Example:

g.setColor(Color.GREEN);

Polygon poly = new Polygon();

poly.addPoint(10,

poly.addPoint(50,

poly.addPoint(90,

g.fillPolygon(poly);

Polygons

18

DrawingPanel p = new DrawingPanel(100, 100);

Graphics g = p.getGraphics();

Let’s add a magenta triangle to your LearningGraphics class:

g.setColor(Color.MAGENTA);

Polygon poly = new Polygon();

poly.addPoint(10, 90);

poly.addPoint(50, 10);

poly.addPoint(90, 90);

g.fillPolygon(poly);

• Once your Drawing Panel looks like this,Submit your LearningGraphics.java file.

19

Try it Out

Superimposing Shapes

20

• When ≥ 2 shapes occupy the same pixels, the last drawn "wins."

import java.awt.*;

public class Car {

public static void main(String[] args) {

DrawingPanel panel = new DrawingPanel(200,

panel.setBackground(Color.LIGHT_GRAY);

Graphics g = panel.getGraphics();

g.setColor(Color.BLACK);

g.fillRect(10, 30, 100, 50);

g.setColor(Color.RED);

g.fillOval(20, 70, 20, 20);

g.fillOval(80, 70, 20, 20);

g.setColor(Color.CYAN);

g.fillRect(80, 40, 30, 20);

}

}

100);

BJP Book

21

// Draws a Building Java Programs textbook

// with DrawingPanel.

import java.awt.*;

public class Book {

public static void main(String[] args) {

DrawingPanel panel = new DrawingPanel(200,

panel.setBackground(Color.WHITE);

Graphics g = panel.getGraphics();

150);

g.fillRect(20, 35 + 10 * i, 10 + 10 * i, 9);

}

}

}

g.setColor(Color.CYAN);

g.fillRect(20, 35, 100, 100);

// cyan background

g.setColor(Color.WHITE);

g.drawString("BJP", 70, 55);

// white "bjp" text

g.setColor(new Color(191, 118,

for (int i = 0; i < 10; i++) {

73)); // orange

//"bricks"

Using Methods to Draw Shapes

22

• To draw in a method, you must pass Graphics g to it.// Draws many BJP textbooks using parameters.

import java.awt.*;

public class Book2 {

public static void main(String[] args) {

DrawingPanel panel = new DrawingPanel(450,

panel.setBackground(Color.WHITE);

Graphics g = panel.getGraphics();

180);

// draw three books at different locations

drawBook(g,

drawBook(g,

drawBook(g,

20, 35);

150, 70);

300, 10);

}

...

, cont'd.

23

...

// Draws a BJP textbook at the given

public static void drawBook(Graphics

g.setColor(Color.CYAN);

g.fillRect(x, y, 100, 100);

x/y position.

g, int x, int y) {

// cyan background

g.setColor(Color.WHITE);

g.drawString("BJP", x + 50,

//

y + 20);

white "bjp" text

g.setColor(new Color(191, 118, 73));

for (int i = 0; i < 10; i++) { //

g.fillRect(x, y + 10 * i, 10 * (i

orange "bricks"

+ 1), 9);

}

}

}

Generalize for any size

24

// Draws many sized BJP textbooks using parameters.

import java.awt.*;

public class Book3 {

public static void main(String[] args) {

DrawingPanel panel = new DrawingPanel(520, 240);

panel.setBackground(Color.WHITE);

Graphics g = panel.getGraphics();

// draw three books at different locations/sizes

drawBook(g,

drawBook(g,

drawBook(g,

20, 35, 100);

150, 70, 60);

300, 10, 200);}

...

Resizable solution, cont'd.

25

...

// Draws a book of the given size at the given position.

public static void drawBook(Graphics g,

g.setColor(Color.CYAN);

g.fillRect(x, y, size, size);

int x, int y, int size) {

// cyan background

g.setColor(Color.WHITE);

g.drawString("BJP", x + size/2,

// white "bjp" text

y + size/5);

g.setColor(new Color(191, 118, 73));

// orange "bricks"

// x

// y

// width

// height

for (int i = 0; i < 10; i++)

g.fillRect(x,

y + size/10 *

{

i,

size/10 * (i + 1),

size/10 - 1);}

}

}

More DrawingPanel Methods

26

• panel.clear();

Erases any shapes that are drawn on the drawing panel.

• panel.setWidth(width); panel.setHeight(height); panel.setSize(width, height);

Changes the drawing panel's size to the given value(s).

• panel.save(filename);

Saves the image on the panel to the given file (String).

• panel.sleep(ms);

Pauses the drawing for the given number of milliseconds.

Animation with sleep

27

• DrawingPanel's sleep method pauses your program for

a given number of milliseconds.

• You can use sleep to create simple animations.DrawingPanel panel = new DrawingPanel(250,

Graphics g = panel.getGraphics();

200);

g.setColor(Color.BLUE);

for (int i = 1; i <= 10; i++) {

g.fillOval(15 * i, 15 * i, 30,

panel.sleep(500);

}

30);

Face.javaimport java.awt.*;

/**

* Draws a face

* @author YOUR NAME

*/

public class Face {

/**

* Declares the variables, computes the

* position, and prints the results.

* @param args command line arguments (not used)

*/

public static void main(String[] args) {

DrawingPanel panel = new DrawingPanel(220, 150);

Graphics g = panel.getGraphics();

g.setColor(Color.BLACK);

g.drawOval(10, 30, 100, 100); // face outline

g.setColor(Color.BLUE);

g.fillOval(30, 60, 20, 20); // eyes

g.fillOval(70, 60, 20, 20);

g.setColor(Color.RED);

g.drawLine(40, 100, 80, 100); // mouth

}

}

In-class Exercise – Face.java• Go to the moodle page and work on the Face.java assignment.• Modify the Face.java program to draw the graphical output shown

below. • Do so by writing a parameterized static method that draws a face

at a given position – public static void drawFace(Graphics g, int x, int y)

• The window size should be changed to 320 x 180 pixels• The two faces' top-left corners are at (10, 30) and (150, 50). • This is Exercise 3G.3 in the textbook.• Magic numbers are okay for this program.

Lab Exercise – Face2.java• Go to the moodle page and work on the Face2.java assignment.

• Modify your Face program from the previous exercise

into a new class Face2 to draw the new output shown

below. • The window size should be changed to 520 x 180 pixels• The faces' top-left corners are at (10, 30), (110, 30),

(210, 30), (310, 30), and (410, 30). • Draw the figures using a loop to avoid redundancy.• This is Exercise 3G.4 in the textbook.• Magic numbers are okay for this program.

top related