Using Graphics Building Java Programs Supplement 3G Introduction - - PowerPoint PPT Presentation

using graphics building java
SMART_READER_LITE
LIVE PREVIEW

Using Graphics Building Java Programs Supplement 3G Introduction - - PowerPoint PPT Presentation

Using Graphics Building Java Programs Supplement 3G Introduction So 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


slide-1
SLIDE 1

Using Graphics Building Java Programs Supplement 3G

slide-2
SLIDE 2

Introduction

So 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

  • ther than using the console.
slide-3
SLIDE 3

Review

Calling static methods from another class: ❑ Classname.methodname(actual parameters);

double square = Math.pow (x, 2);

Calling (non-static) methods on an instance

  • f a class (object):

❑ variablename.methodname(actual parameters);

Scanner console = new Scanner(System.in); int userInput = console.nextInt();

slide-4
SLIDE 4

Graphical Objects

We 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.

slide-5
SLIDE 5

DrawingPanel Basics

DrawingPanel 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);

slide-6
SLIDE 6

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

slide-7
SLIDE 7
  • 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

slide-8
SLIDE 8

Graphics Basics

Graphics 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();

slide-9
SLIDE 9

Graphics methods

We 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

slide-10
SLIDE 10

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 LearningGraphics Class (after the creation of the DrawingPanel object): Graphics g = panel.getGraphics(); g.fillRect(100, 100, 100, 200); g.drawRect(0, 0, 100, 100);

10

slide-11
SLIDE 11

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.

slide-12
SLIDE 12
  • 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

1 2

slide-13
SLIDE 13

Using Color colors

1 3

  • 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);

slide-14
SLIDE 14

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

slide-15
SLIDE 15
  • T
  • 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 LearningGraphics class:

// white outline of circle g.setColor(Color.WHITE); g.drawOval(200, 200, 100, 100);

15

Outlining Shapes

slide-16
SLIDE 16
  • 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

slide-17
SLIDE 17

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

slide-18
SLIDE 18

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();

slide-19
SLIDE 19

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

slide-20
SLIDE 20

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);

slide-21
SLIDE 21

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"

slide-22
SLIDE 22

Using Methods to Draw Shapes

22

  • T
  • 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); } ...

slide-23
SLIDE 23

, 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

  • range "bricks"

+ 1), 9); } } }

slide-24
SLIDE 24

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); } ...

slide-25
SLIDE 25

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); } } }

slide-26
SLIDE 26

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.

slide-27
SLIDE 27

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);

slide-28
SLIDE 28

Face.java

import 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 } }

slide-29
SLIDE 29

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.
slide-30
SLIDE 30

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.