Introduction to Computation and Problem Solving Class 17: Lab: The Graphics 2D API 1 Prof. Steven R. Lerman and Dr. V. Judson Harward.

Slides:



Advertisements
Similar presentations
UID – Swing and Graphics Chris Coleman
Advertisements

Chapter 13 Graphics.
Chapter 18 Building the user interface. This chapter discusses n Javas graphical user interface. n Swing: an enhancement of a library called the Abstract.
Custom Painting Gestione della Grafica customizzata Vedi anche:
1 Inheritance Classes and Subclasses Or Extending a Class.
1 Applets Programming Enabling Application Delivery Via the Web.
Applets and Graphics.
Copyright © 2003 Pearson Education, Inc. Slide 1.
User Interfaces II GUI – Awt, Swing, Web
1 Introduction to Computation and Problem Solving Class 23: Introduction to Data Structures: Stacks and Queues Prof. Steven R. Lerman and Dr. V. Judson.
Introduction to Computation and Problem
10 Copyright © 2005, Oracle. All rights reserved. Reusing Code with Inheritance and Polymorphism.
15 Copyright © 2005, Oracle. All rights reserved. Adding User Interface Components and Event Handling.
View-Based Application Development Lecture 1 1. Flows of Lecture 1 Before Lab Introduction to the Game to be developed in this workshop Comparison between.
Image Navigator Help Session. Review Graphics2D class for drawing shapes in a component – paintComponent(Graphics g) – Graphics2D g2 = (Graphics2D)g;
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.
OLD BUSINESS : Lets talk about the next exam Project proposals – Functional Definitions Go over homework – NEW BUSINESS: Chapter 4 today GUIs Assignment.
1 Graphical User Interfaces AWT and Swing packages Frames and Panels Components Nested Panels Images Reading for this Lecture: L&L, 3.9 – 3.11.
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.
Fun with Swing Chapter 9. Overview Swing vs. AWT Creating windows and panels. Displaying formatted text in panels. Drawing graphics (lines, circles, etc.)
Graphical User Interfaces
IT300: Introduction to Computer Graphics
A lesson approach © 2011 The McGraw-Hill Companies, Inc. All rights reserved. a lesson approach Microsoft® PowerPoint 2010 © 2011 The McGraw-Hill Companies,
PSSA Preparation.
Chapter 11 Creating Framed Layouts Principles of Web Design, 4 th Edition.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 30 - Dynamic HTML: Structured Graphics ActiveX Control Outline 30.1Introduction 30.2Shape Primitives.
Lesson One: The Beginning
Web Design & Development Lecture 19. Java Graphics 2.
1 More on Applets Overview l Changing Colors l Changing Fonts & Styles l Applet Life-Cycle l Input using Dialog Window l Input using HTML parameters l.
Frame Windows A frame object is used to create a graphical frame window. This frame is used to show information in a graphical application. The JFrame.
CSE 1341 Honors Professor Mark Fontenot Southern Methodist University Note Set 21.
Chapter 16 Graphical User Interfaces John Keyser’s Modifications of Slides by Bjarne Stroustrup
Chapter 2: Using Objects Part 2. Assume you wish to test the behaviour of some method. This is accomplished by providing a tester class: Supply a main.
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?
Graphics Programming. Introduction GOAL: Build the Indexer Client Event-driven vs. Sequential programs Terminology – Top-level windows are called “frame.
Zhang & Liang, Computer Graphics Using Java 2D and 3D (c) 2007 Pearson Education, Inc. All rights reserved. 1 Chapter 2 2D Graphics: Basics.
Graphics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Problem Solving 6 GUIs and Event Handling ICS-201 Introduction to Computing II Semester 071.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Applets Graphical Java programs Run inside web browser Platform-neutral Easy deployment--loads when needed Secure.
Georgia Institute of Technology Drawing in Java – part 2 Barb Ericson Georgia Institute of Technology September 2005.
Chapter 4 (Horstmann’s Book) Interface Types and Polymorphism: Graphics, Timer, Animation Hwajung Lee.
CSC1401 Drawing in Java - 2. Reminder from last class How do you save your modified picture? String filename = …; Picture stevePicture = new Picture(filename);
Chapter 5 Programming Graphics. Chapter Goals To be able to write simple applications To display graphical shapes such as lines and ellipses To use colors.
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
Chapter 5 Programming Graphics. Chapter Goals To be able to write applications with simple graphical user interfaces To display graphical shapes such.
Graphical User Interface Bonus slides Interaction Between Components & Drawing.
More Java Drawing in 2D Animations with Timer. Drawing Review A simple two-dimensional coordinate system exists for each graphics context or drawing surface.
CMSC 341 Building Java GUIs. 09/26/2007 CMSC 341 GUI 2 Why Java GUI Development? Course is about Data Structures, not GUIs. We are giving you the opportunity.
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.
Graphics Programming. In this class, we will cover: The difference between AWT and Swing Creating a frame Frame positioning Displaying information in.
1 L38 Graphics and Java 2D™ (3). 2 OBJECTIVES In this chapter you will learn:  To understand graphics contexts and graphics objects.  To understand.
Java Review Structure of a graphics program. Computer Graphics and User Interfaces Java is Object-Oriented A program uses objects to model the solution.
Web Design & Development Lecture 18. Java Graphics.
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.
Chapter 28 - Java Graphics and Java2D Outline 28.1Introduction 28.2Graphics Contexts and Graphics Objects 28.3Color Control 28.4Font Control 28.5Drawing.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
Java Applets: GUI Components, Events, Etc. Ralph Westfall June, 2010.
(C) 2010 Pearson Education, Inc. All rights reserved.  Class Graphics (from package java.awt) provides various methods for drawing text and shapes onto.
Introduction to Java Chapter 8 - Introduction to Java Graphics1 Chapter 8 Introduction to Java Graphics.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 2 – Welcome Application Introduction to Graphical.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
CPCS 391 Computer Graphics Lab One. Computer Graphics Using Java What is Computer Graphics: Computer graphics are graphics created using computers and,
10/20/2005week71 Graphics, mouse and mouse motion events, KeyEvent Agenda Classes in AWT for graphics Example java programs –Graphics –Mouse events –Mouse.
12 Graphics and Java 2D™.
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.
Presentation transcript:

Introduction to Computation and Problem Solving Class 17: Lab: The Graphics 2D API 1 Prof. Steven R. Lerman and Dr. V. Judson Harward

2 The Origins of the Java® Graphics 2D API The original Java® GUI toolkit, the AWT, was a quick and dirty solution. It used native peer components to draw all widgets. Swing draws all components except the top level containers using Java® methods rather than relying on platform specific widgets. To do this, Swing required improved graphics. The Java® 2D API was born as enabling technology for Swing. There is now a Java® 3D API also. See tutorial at

3 Java® Graphics Architecture Swing Java® AWT Java® 2D Graphics API Platform Windowing System Platform Graphics Architecture

4 NgonApp Custom Drawing Swing Components: JLabel and JTextField

5 So, How Do I Draw in Java® You might think that if you want to do your own drawing in Java®, you do it in the main thread just as you create a GUI out of components in the main thread. In fact, you have to create components on which you draw like all your other GUI components in the main thread. But the drawing has to be done in the event thread. And to understand why, we need to start by considering when drawing happens.

6 When Does a GUI Get Drawn? On initial display (but not necessarily when the program gets started) When the display gets damaged. For example when it gets hidden and then reexposed. When the content changes, and Swing or the programmer calls for a refresh (repaint( )). – Remember the tick( ) method from the previous lab? public void tick( ) { minutes++; // increment # of minutes repaint(); // refresh clock display }

7 How does a GUI Get Drawn? Swing schedules the drawing. It may combine multiple redraw requests that occur in rapid succession. Swing calls the following three methods in order (on the event thread): paintComponent( ) paintBorder( ) paintChildren( ) The last recursively paints a container's children.

8 How to Do Custom Drawing Standard Swing components like JLabel and JComboBox use paintComponent() to draw themselves. If you want to do custom drawing, extend a container class, usually JPanel, and override paintComponent( ). Use calls from the 2D API in paintComponent( ) to draw what you want on the JPanel background. Override getPreferredSize() or call setPreferredSize() to size JPanel to your drawing.

9 The Graphics Class paintComponent() is called with argument Graphics g, that serves as a drawing toolkit initialized to the component's defaults. In more recent versions of the JDK, the argument is really a Graphics2D object, which extends Graphics for the 2D API. So cast it. Graphics was the original AWT class. Using the 2D API usually starts off like this: public void paintComponent( Graphics g ) { super.paintComponent( g ); Graphics2D g2 = (Graphics2D) g; //drawing commands go here }

10 Where Does the Graphics Argument Come From? The Graphics argument to the paintComponent( ) method is a snapshot of your component's default graphics values like font and drawing color at the moment the paint methods are called. It is only a copy of these values. Each time the paint methods are called, you get a new version of Graphics. No changes you make to a Graphics instance in one call to paintComponent( ) are remembered the next time you enter the method. And no changes, like setFont( ) are propagated back to the component itself.

11 Basic 2D API Operations You can use the Graphics2D argument to 1. draw outline figures using the method public void draw( Shape s ) 2. draw filled figures using the method public void fill( Shape s ) You can use the Graphics or Graphics2D argument to 3. draw an image using one of the methods: public void drawImage(... ) 4. draw a text string using the methods: public void drawString(... )

12 Graphics 2D Rendering Context Much of the power of the 2D API comes from the users ability to set attributes of the Graphics2D object known collectively as the rendering context: – public void setStroke(Stroke s) – public void setPaint(Paint p) – public void setFont(Font f) – public void setComposite(Composite c) – public void setTransform(Transform t) – public void setRenderingHints(Map m)

13 Custom Drawing Template import java.awt.*; // for Graphics2D, Paint, Shape, … import java.awt.geom.*; // for concrete Shape classes import javax.swing.*; // for JPanel, etc public class MyPanel extends JPanel {... public void paintComponent( Graphics g ) { super.paintComponent( g ); Graphics2D g2 = (Graphics2D) g;... g2.setPaint/Stroke/Font/etc(...); Shape s = new Shape2D.Float/Double(... ); g2.draw/fill( s );...

14 2D Shapes Shape is an interface defined in java.awt, but the classes that implement Shape are all defined in java.awt.geom. Shapes all come in two versions, one with high precision coordinates and one with low, e.g.: Ellipse2D.Double // high precision Ellipse2D.Float // low precision Each shape has a different constructor arguments, doubles or floats depending on whether they are high precision or low.

15 Creating an Ellipse Shape s = new Ellipse2D.Double( 100.0, // x 50.0, // y 300.0, // width // height ); 100.0

16 Graphics2D Coordinate System The Graphics2D object uses a variety of world coordinates (as opposed to device coordinates) that Java® calls user space. Graphics2D shapes and operations are defined in floating point ( float or double ) but the Y coordinate increases downwards. Some Graphics2D calls only take floats. The floating point coordinates are designed to make your graphics independent of the output device. The 2D API is designed for printing as well as output to screens at different resolutions.

17 The Graphics2D Default Transformation The 2D rendering pipeline applies a geometric transformation to map user space to device space. The default transformation maps 1.0 user space units to ~1/72 of an inch, which happens to be the average pixel size on a screen or a printers point size on a printer. So unless you do something special, 2D drawing defaults to pixel coordinates.

18 Ellipse.java, 1 import java.awt.*; import java.awt.geom.*; import javax.swing.*; Public class Ellipse extends JPanel { private Shape ellipse; public static void main( String[] args ) { JFrame frame = new JFrame( "Ellipse" ); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add( new Ellipse(), "Center" ); frame.setSize( 650, 300 ); frame.setVisible( true ); }

19 Ellipse.java, 2 public Ellipse() { ellipse = new Ellipse2D.Double( 100.0, 50.0, 300.0, ); setBackground( Color.white ); setOpaque( true ); } public void paintComponent( Graphics g ) { super.paintComponent( g ); Graphics2D g2 = (Graphics2D) g; g2.setPaint( Color.red ); g2.fill( ellipse ); }

20 Stroke s and Paint Stroke is an interface, and BasicStroke is the only supplied class that implements it. You can think of Stroke as a pen and Paint as the corresponding ink. A BasicStroke can have width and a dashed pattern as well as options that define how a Stroke ends and treats joins. Color implements Paint so a Java® Color is the simplest sort of Paint. Paint s can use a pattern or texture (for example, plaid).

21 GeneralPath s How can you define your own Shape ? Use a GeneralPath. You define the outline by adding path components that can be Shape s, Line s, or curves. void append( Shape s, boolean connect ); void lineTo( float x, float y ); void moveTo( float x, float y ); void quadTo( float x1, float y1, float x2, float y2 ) ; void closePath();

22 Null.java, 1 public class Null extends JPanel { private GeneralPath slash0; private Stroke brush; public Null( ) { setPreferredSize( new Dimension( 600, 400 )); setBackground( Color.white ); setOpaque( true ); brush = new BasicStroke( 10, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND ); slash0 = new GeneralPath(); Ellipse e = new Ellipse2D.Double( 220,100,160,200 ); slash0.append( e, false ); slash0.moveTo( 350, 100 ); slash0.lineTo( 250, 300 ); }

23 Null.java, 2 public void paintComponent( Graphics g ) { super.paintComponent( g ); Graphics2D g2 = (Graphics2D) g; g2.setStroke( brush ); g2.setPaint( Color.blue ); /* g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); **/ g2.draw( slash0 ); }

24 Drawing Text Up until now we have presented text using JLabel s. You can draw text directly using the Graphics2D methods: public void drawSting( String s, int x, int y ); public void drawSting( String s, float x, float y ); The coordinates define the left end of the baseline on which the text appears.

25 Signature.java, 1 public class Signature extends JPanel { private String name = "Judson Harward"; private Font signFont; private Stroke underStroke; private Line2D underline; public Signature() { setPreferredSize( new Dimension( 600, 400 )); setBackground( Color.white ); setOpaque( true ); underStroke = new BasicStroke( 1 ); underline = new Line2D.Float( 100F,300F,500F,300F ); signFont = new Font( "Serif", Font.ITALIC, 24 ); }

26 Signature.java, 2 public void paintComponent( Graphics g ) { super.paintComponent( g ); Graphics2D g2 = (Graphics2D) g; g2.setStroke( underStroke); g2.setPaint( Color.lightGray ); g2.draw( underline ); g2.setFont( signFont ); g2.setPaint( Color.blue ); g2.drawString( name, 110F, 300F ); }

27 Exercise: Building NgonApp, 1 You are going to build an application that illustrates how the area of an inscribed polygon approaches that of a circle as the number of sides increases. Download the files NgonApp.java and NgonView.java from the lecture directory on the class web site and save them into a new directory. Create a new project in Forte and mount the directory that you just saved the files into. Compile and run.

28 Building NgonApp, 2 NgonApp should look like this before you change anything:

29 Building NgonApp, 3 Let's examine the source code. NgonApp.java contains the main() method and the class that lays out the GUI. You will not have to change it. Note that it creates an instance of NgonView and puts it in the center of the content pane. It uses a JTextField to ask for the number of polygon sides. When you type a return into a JTextField it will issue an action event. Check how that ActionEvent is handled. Remember that it must be an error to specify a polygon with less than 3 sides. We will handle that error in NgonView.

30 NgonApp, 1 st Version After Adding Code JFrame with BorderLayout NgonView extends JPanel JPanel with FlowLayout

31 Initial NgonView NgonView is the class that does all the custom drawing. The initial version has just the paintComponent() code to draw the background and certain helper methods. – void setSides(int n) : installs a new number of polygon sides – double getRegPolyArea( int n ): calculates the area of a regular polygon with n sides inscribed in the unit circle – Dimension getPreferredSize(): returns a fixed size – float transX( float x ), float transY( float y ): we'll come back to these in a minute

32 NgonApp, version 1 Modify NgonView.java so that it will either display an error message or display the polygon area every time the number of sides changes. You will need to create an appropriate font, but then should only have to modify paintComponent ( ) to draw the appropriate message at (textX, textY). Compile and test. Now modify paintComponent() again to draw a blue circle with a stroke two pixels wide as shown on the next slide. Don't use transX/transY(). Compile and test. Now try filling the circle in yellow. Do you want to draw the outline first and then fill, or vice versa? Why?

33 NgonView, version 1 Positioning the Circle

34 NgonApp, version 2 In order to draw a regular polygon inscribed in a unit circle, it is going to be much easier to think in terms of a coordinate system with its origin at the center of the circle as in the following slide. Note that the scale is set so that the circle is a unit circle. transX() and transY() translate points in this coordinate system to the pixel coordinates of the window. Test it. The center of the unit circle is (0,0). What is transX(0) ? transY(0) ? See if you can recreate the filled circle on NgonView by using transX/Y() to define the upper left corner of the bounding box and SCALE to define the width and height.

35 NgonView, v2 Using Transformed Coordinates

36 NgonView, Transformed Coordinates In order to draw a regular polygon inscribed in a unit circle, it is going to be much easier to think in terms of a coordinate system with its origin at the center of the circle as in the following slide. Note that the scale is set so that the circle is a unit circle. transX() and transY() translate points in this coordinate system to the pixel coordinates of the window. Test it. The center of the unit circle is (0,0). What is transX(0) ? transY(0) ? See if you can recreate the filled circle on NgonView by using transX/Y() to define the upper left corner of the bounding box and SCALE to define the width and height. Compile and test.

37 NgonView, Inscribing the Polygon

38 NgonView, Inscribing the Polygon, 2 Now use a GeneralPath and transX/Y() to create the filled inscribed polygon. Start the path at (1,0). Calculate the central angle between vertices. Use a loop to generate the first n-1 sides, and closePath() to generate the last side. Remember that because y increases downwards the first vertex will be below the X-axis, not above as in regular coordinate geometry. Add the appropriate method call to paintComponent() to fill the polygon. Compile and test.