Draw Shapes Introduction to simple graphics. What is a graphics context? An instance of the Graphics class Graphics is ABSTRACT! You can extend Graphics.

Slides:



Advertisements
Similar presentations
UID – Swing and Graphics Chris Coleman
Advertisements

Custom Painting Gestione della Grafica customizzata Vedi anche:
Applets and Graphics.
Chapter 15 Graphics. To paint, you need to specify where to paint. Each component has its own coordinate system with the origin (0, 0) at the upper-left.
Copyright 2006 by Pearson Education 1 Building Java Programs Supplement 3G: Graphics.
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Laboratory Study II October, Java Programming Assignment  Write a program to calculate and output the distance traveled by a car on a tank of.
Graphics You draw on a Graphics object The Graphics object cannot directly be created by your code, instead one is generated when the method paintComponent.
Graphics Chapter 16.  If you want to draw shapes such as a bar chart, a clock, or a stop sign, how do you do it?
Cosc 5/4730 Blackberry Drawing. Screen size With Blackberry devices, they have a known screen size in pixels. If you are programming for specific device.
Graphics Programming. Introduction GOAL: Build the Indexer Client Event-driven vs. Sequential programs Terminology – Top-level windows are called “frame.
PHY-102 SAPIntroductory GraphicsSlide 1 Introductory Graphics In this section we will learn how about how to draw graphics on the screen in Java:  Drawing.
Zhang & Liang, Computer Graphics Using Java 2D and 3D (c) 2007 Pearson Education, Inc. All rights reserved. 1 Chapter 2 2D Graphics: Basics.
LAB SESSION 7 Graphical user interface Applet fundamentals Methods in applets Execution of an applet Graphics class.
Graphics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Georgia Institute of Technology Drawing in Java – part 2 Barb Ericson Georgia Institute of Technology September 2005.
CSC1401 Drawing in Java - 2. Reminder from last class How do you save your modified picture? String filename = …; Picture stevePicture = new Picture(filename);
More Java Drawing in 2D Animations with Timer. Drawing Review A simple two-dimensional coordinate system exists for each graphics context or drawing surface.
Java Graphics Section 1 - Multi-File Graphics Programs Section 2 - The Coordinate System and Graphics Context g Section 3 - The Java Drawing and Painting.
UID – Swing and Graphics Boriana Koleva
GUI and Swing, part 2 The illustrated edition. Scroll bars As we have previously seen, a JTextArea has a fixed size, but the amount of text that can be.
Slides prepared by Rose Williams, Binghamton University Chapter 19 Swing II.
Copyright 2006 by Pearson Education 1 Building Java Programs Supplement 3G: Graphics.
1 L38 Graphics and Java 2D™ (3). 2 OBJECTIVES In this chapter you will learn:  To understand graphics contexts and graphics objects.  To understand.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Java Graphics Applets.
Web Design & Development Lecture 18. Java Graphics.
CS324e - Elements of Graphics and Visualization Java2D Graphics.
Graphics. Graphics Features in Java Topics to be covered Topics to be covered Graphics Basics Graphics Basics Coordinate System Coordinate System Graphics,
Chapter 16: Graphics. Objectives Learn about the paint() and repaint() methods Use the drawString() method to draw String s using various fonts and colors.
Draw Shapes Introduction to simple graphics. What is a Component? A class that resides in the java.awt package Examples include: –Button, java.awt.Button.
1 Graphical User Components (II) Outline JTextArea Creating a Customized Subclass of JPanel JPanel Subclass that Handles Its Own Events Windows: Additional.
2D Graphics: Rendering Details
CSE 219 Computer Science III Images. HW1 Has been posted on Blackboard Making a Game of Life with limited options.
Chapter 15 Graphics and Java 2D™ Java How to Program, 8/e (C) 2010 Pearson Education, Inc. All rights reserved.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 28 - Java Graphics and Java2D Outline 28.1Introduction.
Chapter 28 - Java Graphics and Java2D Outline 28.1Introduction 28.2Graphics Contexts and Graphics Objects 28.3Color Control 28.4Font Control 28.5Drawing.
 Pearson Education, Inc. All rights reserved. 1 Ch 12 Graphics and Java 2D In this chapter you will learn:  To understand graphics contexts.
Advanced User Interfaces with Java SD’98 - Session 3206 Ted Faison Faison Computing Inc.
Chapter 15Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 15 l Basic Figures l Colors l Fonts and Other Text Details.
Graphics & Java 2D Drawing Two Dimensional Shapes Controlling Fonts Controlling Colors.
Applets Applet is java program that can be embedded into HTML pages. Java applets runs on the java enabled web browsers such as mozilla and internet explorer.
Java Graphics. Review 3 kinds of elements in components API? Layout managers Events Extend vs. Implement.
1 Chapter 3 2D Graphics: Rendering Details  Color spaces, paints stroke types  Affine transforms including translation, rotation, scaling, shearing,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Introduction to Android (Part.
1 Building Java Programs Supplement 3G: Graphics These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold,
(C) 2010 Pearson Education, Inc. All rights reserved.  Class Graphics (from package java.awt) provides various methods for drawing text and shapes onto.
Georgia Institute of Technology Drawing in Java Barb Ericson Georgia Institute of Technology August 2005.
Merete S COLLEGEFACULTY OF ENGINEERING & SCIENCE Graphics ikt403 – Object-Oriented Software Development.
Introduction to Java Chapter 8 - Introduction to Java Graphics1 Chapter 8 Introduction to Java Graphics.
Painting (Chapter 12) Java Certification Study Group January 25, 1999 Mark Roth.
Creating Graphics in Java CSE301 University of Sunderland Harry R Erwin, PhD.
Chapter 2: Graphics In Java Basics of classes –instance variables –methods –overriding methods Graphics class (drawing routines) Other classes –Color –Font.
Graphics and Java2D Chapter Java Coordinate System Origin is in _____________ corner –Behind title bar of window X values increase to the ________.
CSI 3125, Preliminaries, page 1 AWT. CSI 3125, Preliminaries, page 2 AWT Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based.
Introduction to Graphics. Graphical objects To draw pictures, we will use three classes of objects: –DrawingPanel : A window on the screen. –Graphics.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Basic Graphics 03/03/16 & 03/07/16 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Georgia Institute of Technology Drawing in Java – part 2 Dr Usman Saeed Assistant Professor Faculty of Computing and Information Technology North Jeddah.
Intro to Graphics from Chapter 2 of Java Software Solutions
Eleventh Graphics in Java.
12 Graphics and Java 2D™.
Graphics Chapter 6 Copyright © 2000 W. W. Norton & Company.
JAVA 2 Design and programming of GUI
Basic Graphics Drawing Shapes 1.
Workshop for Programming And Systems Management Teachers
Java Graphics The basic rendering mechanism is the drawing system that controls when and how programs can draw on a graphics component. When a component.
4.14 GUI and Graphics Case Study: Creating Simple Drawings (Cont.)
12 Graphics and Java 2D™.
Workshop for Programming And Systems Management Teachers
Presentation transcript:

Draw Shapes Introduction to simple graphics

What is a graphics context? An instance of the Graphics class Graphics is ABSTRACT! You can extend Graphics You can get instances of the Graphics class  From the paint method  From an instance of an java.awt.Image  From a java.awt.Component

Why do I need a graphics context? To get access to simple 2D draw methods. - Draw Business graphics - Draw Vectors into the screen. - Draw text - Draw java.awt.Images - simple shapes (2D) - I can print vectors, and bit map.

Built-in Graphics Functions The Java Graphics Objects includes dozens of drawing functions:  drawLine()  drawOval()  drawPolygon()  drawRect()  draw3DRect()  fillOval()  fillRect()

Drawing Draw a yellow-filled rectangle: g.setColor (new Color (255,255,206)); g.fillRect (50, 50, 215,100); Draw a black perimeter around the yellow rectangle. g.setColor (Color.black); g.drawRect (50,50,215,100); Draw a line underneath the welcome message. g.drawLine (80,105,227,105);

Who calls Paint? public void paint(Graphics g) {...  Not the programmer  Not the JVM  AWT Event Dispatcher (it runs in a thread).  called in response to a repaint invocation!  repaint()  repaint(1000); // paint invoked in 1 second

When does the Damage control manager invokes repaint? If there is damage, damage control for the window causes repaint. Window resize Window exposed Component demands. repaint(int x, int y, int w, int h)

Damage control manager AWT Dispatcher Component repaint Damage caused update Window system

Dimensions Windows have dimension let Window w = new Window(); //then Dimension d = w.getSize(); Components have dimensions too. Int w = d.width; Int h = d.height;

Coordinates Integers 0,0 (w,h) x y

Custom painting (1) Occurs between background and border Extend component and customise  JPanel recommended e.g. class myPaintingPanel extends JPanel {  can also use atomic components e.g. class myPaintingButton extends JButton { Code goes in overridden paintComponent() method  public void paintComponent(Graphics g) {

Custom painting (2) When writing custom painting code  should not reproduce painting functionality of any other Swing component Before doing anything else in paintComponent()  invoke super.paintComponent() or  setOpaque(false)

Painting coordinates Component sizes in pixels  (0,0) at top left corner  (width-1,height-1) at bottom right corner Border sizes (e.g. a 1-pixel border)  (1,1) at top left  (width-2, height-2) at bottom right General painting area for b pixel border  [ {b,b} : {w-(b+1), h-(b+1)} ]

Getting painting coordinates Use component getWidth() and getHeight() Get border sizes with getInsets()  e.g. to get width and height of custom painting area use something like:  Insets insets = getInsets(); int currentWidth = getWidth() - insets.left - insets.right; int currentHeight = getHeight() - insets.top - insets.bottom;

Repainting custom paints Calling repaint() method requests a repaint to occur  repaint() paints whole component & any others that need it if transparent  repaint(int leftx,int lefty,int width,int height); only repaints a specified area Component painted after all pending events dispatched. Painting should be kept short - Done in event thread - slows GUI

Formula for a circle Implicit formula  (X-xc)^2 + (Y-yc)^2 = R^2 Parametric Formula  X = sin(t)+xc  Y = cos(t)+yc  T is in the range from 0 to 1 inclusive

For a line Y=mx+b, where m = slope, b = y intercept F(t) = P0(1-t)+P1(t) P0 = (x0,y0) P1=(x1,y1) F(t)=P0-p0t+p1t=t(p1-p0)+p0

Vector Graphics

Legend Stock price, sample rate (once every 30 sec).

Drawing text strings Graphics2D public void drawString(String s, int x, int y) Draws given string with its first letter's bottom-left corner at the given location.  The string is drawn using the Graphics2D's current color and font settings.  Before drawing the string, you can set the font, color, and other attributes. (see next slides)

Fonts Graphics2D  public void setFont(Font f) Sets this Graphics context to start writing text in the given font. (Forgotten at end of paintComponent call!)

java.awt.Font Text styles used when drawing Strings on the panel  public Font( String name, int style, int size )  some predefined font names: "Serif", "SansSerif", "Monospaced"  font styles (can be combined with + operator): Font.BOLD Font.ITALIC Font.PLAIN

Drawing Arcs Arcs  Outlined Arc g.drawArc(topLeftX, topLeftY, width, height, startAngle, arcAngle);  Filled Arc g.fillArc((topLeftX, topLeftY, width, height, startAngle, arcAngle);

Drawing Rectangles Rectangle  Outlined Rectangle g.drawRect(topLeftX, topLeftY, width, height);  Filled Rectangle g.fillRect(topLeftX,topLeftY,width,height);

Outlined Rounded Rectangle g.drawRoundRect(topLeftX,topLeftY,width,height,a rcWidth,arcHeight);  Filled Rounded Rectangle g.fillRoundRect(topLeftX,topLeftY,width,height,arc Width,arcHeight);

Drawing on a Blank Picture You can make pictures from the “blank” files  They will have all white pixels  640x480.jpg  7inX95in.jpg

create a “blank” picture with a width and height They will also have all white pixels  Picture blankPicture = new Picture(width,height);

Draw a Picture Exercise Create a method that will draw a simple picture  Use at least one rectangle  Use at least one polygon  Use at least one oval  Use at least one arc

Bitmapped Versus Vector Graphics Some applications use vector graphics which are programs that produce the picture  Used in Postscript, Flash, and AutoCAD  Advantages: smaller, easy to change, can be scaled

Precision Drawings draw a stack of filled rectangles starting from the lightest one at the bottom right and the darkest one at the top left.  10 pixels between each  Not easy with drawing packages

Draw Filled Rectangles Method public void drawFilledRectangles(){ Graphics g = this.getGraphics(); Color color = null; // loop 25 times for (int i = 25; i > 0; i--) { color = new Color(i * 10, i * 5, i); g.setColor(color); g.fillRect(0,0,i*10,i*10); }}

Java 2D Graphics – java.awt Newer drawing classes  More object-oriented  Instead of drawOval() or fillOval() you create a Ellipse2D object and ask a 2d graphics object to draw or fill it  Geometric shapes are in the java.awt.geom package

Advanced Drawing  Support for different types of brushes Line thickness, dashed lines, etc  Supports cubic curves and general paths  Drawing of gradients and textures  Move, rotate, scale and shear text and graphics  Create composite images

Java 2D Demo

How To Use Java 2D Cast the Graphics class to Graphics2D  Graphics2D g2 = (Graphics2D) gObj; Set up the stroke if desired (type of pen)  g2.setStroke(new BasicStroke(widthAsFloat));

Set up any Color, GradientPaint, or TexturePaint  g2.setPaint(Color.blue);  g2.setPaint(blueToPurpleGradient);  g2.setPaint(texture); Create a geometric shape  Line2D line2D = new Line2D.Double(0.0,0.0,100.0,100.0); Draw the outline of a geometric shape  g2.draw(line2d); Fill a geometric shape  g2.fill(rectangle2d);

Graphics2D inherits from Graphics Inherits basic drawing ability from Graphics Adds more advanced drawing ability Graphics Graphics2D

Drawing Lines Exercise Create a new method (drawWideX) for adding two wide crossed lines to a picture  passed color  passed line width

Set up the stroke to make the lines thicker  g2.setStroke(new BasicStroke(width));  Draw the lines You can use redMotorcycle.jpg to test.

Colors and paints java.awt.Color (a simple single-colored paint)  public Color(int r, int g, int b)  public Color(int r, int g, int b, int alpha) a partially-transparent color (range 0-255, 0=transparent)

Colors and paints..  public Color brighter(), darker()  public static Color black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, white, yellow java.awt.GradientPaint (smooth transition between 2 colors)  public GradientPaint(float x1, float y1, Color color1, float x2, float y2, Color color2) java.awt.TexturePaint (use an image as a "paint" background)

Shapes (old style) Graphics2D public void drawLine(int x1, int y1, int x2, int y2) public void drawOval(int x, int y, int w, int h) public void fillOval(int x, int y, int w, int h)

Polygons public void drawPolygon(int[] xpoints, int[] ypoints, int len) public void fillPolygon(int[] xpoints, int[] ypoints, int len) public void drawRect(int x, int y, int w, int h) public void fillRect(int x, int y, int w, int h) public void drawArc(...) public void fillArc(...)... Drawing methods for drawing various lines and shapes on a Graphics context. Not recommended to be used  replaced by draw(Shape), fill(Shape) in Graphics2D

Graphics2D shape methods public void draw(Shape s) Draws the outline of the given shape using this Graphics2D 's current pen. public void fill(Shape s) Draws outline and fills inside of given shape. rotate, scale, translate, shear, transform Perform various coordinate transformations on the Graphics2D context.

Shapes (in package java.awt.geom ) Arc2D.Double(double x, double y, double w, double h, double start, double extent, int type) An arc, which is a portion of an ellipse.

Ellipse2D Ellipse2D.Double(double x, double y, double w, double h) An ellipse, which is a generalization of a circle. Line2D.Double(double x1, double y1, double x2, double y2) Line2D.Double(Point p1, Point p2) A line between two points.

Shapes Rectangle2D.Double(double x, double y, double w, double h) A rectangle, which is a generalization of a square.

RoundRectangle2D RoundRectangle2D.Double( double x, double y, double w, double h, double arcx, double arcy) A rounded rectangle. GeneralPath() A customizable polygon.

Methods of to all shapes public boolean contains(double x, double y) public boolean contains(Point2D p) Whether the given point is contained inside the bounds of this shape.

Rectangle public Rectangle getBounds() A rectangle representing the bounding box around this shape. public double getCenterX() / getCenterY() public double getMinX() / getMinY() public double getMaxX() / getMaxY() Various corner or center coordinates within the shape. public boolean intersects(double x, double y, double w, double h) public boolean intersects(Rectangle2D r) Whether this shape touches the given rectangular region.

Strokes (pen styles) Graphics2D  public void setStroke(Stroke s) Sets type of drawing pen (color, width, style) that will be used by this Graphics2D.

java.awt.BasicStroke A pen stroke for drawing outlines  public BasicStroke(float width)  public BasicStroke(float width, int cap, int join)  public BasicStroke(float width, int cap, int join, float miterlimit, float[] dash, float dash_phase) cap: CAP_BUTT, CAP_ROUND, CAP_SQUARE join: JOIN_BEVEL, JOIN_MITER, JOIN_ROUND

Drawing example 1 public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.fill(new Rectangle2D.Double(10, 30, 60, 35)); g2.fill(new Ellipse2D.Double(80, 40, 50, 70)); }

Drawing example 2 public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setPaint(Color.BLACK); g2.fill(new Rectangle2D.Double(10, 30, 100, 50)); g2.setPaint(Color.RED); g2.fill(new Ellipse2D.Double(20, 70, 20, 20)); g2.fill(new Ellipse2D.Double(80, 70, 20, 20)); g2.setPaint(Color.CYAN); g2.fill(new Rectangle2D.Double(80, 40, 30, 20)); }

Drawing example 3 public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setPaint(Color.BLUE); for (int i = 1; i <= 10; i++) { g2.fill(new Ellipse2D.Double(15 * i, 15 * i, 30, 30)); } g2.setPaint(Color.MAGENTA); for (int i = 1; i <= 10; i++) { g2.fill(new Ellipse2D.Double(15 * (11 - i), 15 * i, 30, 30); }}

Using a Graphics Object to Copy an Image public void copy(Picture source, int x, int y){ // get the graphics object Graphics g = this.getGraphics(); // copy the image g.drawImage(source.getImage(),x,y,null); }

Using Graphics2D to Copy an Image public void copy2D(Picture source, int x, int y){ // get the graphics object Graphics g = this.getGraphics(); Graphics g2 = (Graphics2D) g; // copy the image g2.drawImage(source.getImage(),x,y,null); }

Testing the Copy Method Picture p1 = new Picture(FileChooser.getMediaPath("beach. jpg")); Picture p2 = new Picture(FileChooser.getMediaPath("turtle.j pg")); p1.copy2D(p2,194,304); p1.show();

Drawing images Graphics2D public void drawImage(Image i, int x, int y, ImageObserver io) public void drawImage(Image i, int x, int y, int width, int height, ImageObserver io) Draws given image object on this Graphics context with its top-left corner at given location (pass the panel as the ImageObserver ).

Classes for imaging java.awt.Toolkit Gets images from disk or internet  public static Toolkit getDefaultToolkit()  public Image getImage(String filename)  public Image getImage(URL address)

java.awt.MediaTracker Ensures that images are loaded fully  public MediaTracker(Component comp)  public void addImage(Image img, int id)  public void waitForAll() throws InterruptedException java.awt.Image Represents a graphic image (BMP, GIF,...)  public int getWidth(ImageObserver obs)  public int getHeight(ImageObserver obs) java.awt.image.BufferedImage A blank graphic image surface onto which you can draw  public BufferedImage(int w, int h, int type)  public Graphics getGraphics()

Images, continued Code to load an image: Toolkit tk = Toolkit.getDefaultToolkit(); Image img = tk.getImage("myimage.jpg"); MediaTracker mt = new MediaTracker(this); mt.addImage(img, 0); // any ID will do try { mt.waitForAll(); } catch (InterruptedException ie) {}

A helper method to load and return one image public Image loadImage(String filename)

Advanced: anti-aliasing Onscreen text and shapes can have jagged edges, or aliases. These can be removed by smoothing, or anti-aliasing, the panel.

Graphics2D public void setRenderingHint( RenderingHints.Key key, Object value)  Example: g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) ;

Icon/ImageIcon Allows you to put a picture on a button, label or other component public class ImageIcon implements Icon  public ImageIcon(String filename)  public ImageIcon(URL address) in JButton, JRadioButton, JCheckBox, JLabel, etc...  constructor that takes an Icon  public void setIcon(Icon)  public void setSelectedIcon(Icon)  public void setRolloverIcon(Icon)

JToolBar A movable container to hold common buttons, commands, etc

JToolBar public JToolBar() public JToolBar(int orientation) public JToolBar(String title) public JToolBar( String title, int orientation ) Constructs a new tool bar, optionally with a title and orientation; can be JToolBar.HORIZONTAL or VERTICAL, defaults to horizontal public void add(Component comp) Adds the given component to this tool bar's horizontal/vertical flowing layout.

JToolBar : Usage construct toolbar add items (usually buttons) to toolbar add toolbar to edge of BorderLayout of content pane (usually NORTH )  don't put anything in other edges (N/S/E/W)!

Summary Graphics class for simple 2d drawing  Lines, rectangles, ovals, polygons, strings, images Graphics2D for more advanced drawing  Width of paint brush, paint geometric objects Graphics2D inherts from Graphics  Means it can do the same methods  But also adds others