More Java Drawing in 2D Animations with Timer. Drawing Review A simple two-dimensional coordinate system exists for each graphics context or drawing surface.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Web Design & Development Lecture 19. Java Graphics 2.
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.
Examples. // A simple Frame with Rectangle Inside import java.awt.*; import javax.swing.*; import java.awt.geom.*; // For Shapes class rectComponent extends.
Mouse Listeners We continue our examination of GUIs by looking at how to interact with the mouse –Just as Java creates Events when the user interacts with.
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.
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.
Graphic User Interfaces Layout Managers Event Handling.
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.
Chapter 4 (Horstmann’s Book) Interface Types and Polymorphism: Graphics, Timer, Animation Hwajung Lee.
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.
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.
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.
1 Frameworks. 2 Framework Set of cooperating classes/interfaces –Structure essential mechanisms of a problem domain –Programmer can extend framework classes,
Graphics Programming. In this class, we will cover: The difference between AWT and Swing Creating a frame Frame positioning Displaying information in.
Advanced Java Class GUI – part 1. Intro to GUI GUI = Graphical User Interface -- “Gooey” Just because it’s “gooey” does not mean you may write messy code.
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
CS 112 GUI 06 May 2008 Bilkent. Java GUI API Containers: ◦ contain other GUI components. E.g, Window, Panel, Applet, Frame Dialog. Components: ◦ Buttons,
Java Review Structure of a graphics program. Computer Graphics and User Interfaces Java is Object-Oriented A program uses objects to model the solution.
Swing Graphics ● Empty Swing containers have no visual appearance except for a background color ● Every JComponent must have a paintComponent method that.
Graphics and Multimedia. Introduction The language contains many sophisticated drawing capabilities as part of namespace System.Drawing and the other.
1 Interface Types & Polymorphism & introduction to graphics programming in Java.
20-753: Fundamentals of Web Programming Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 16: Java Applets & AWT Fundamentals of Web Programming.
6-2 2D Graphics CSNB544 Mobile Application Development Thanks to Utexas Austin.
1 Graphical User Components (II) Outline JTextArea Creating a Customized Subclass of JPanel JPanel Subclass that Handles Its Own Events Windows: Additional.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 20.1 Test-Driving the Screen Saver Application.
CSE 219 Computer Science III Images. HW1 Has been posted on Blackboard Making a Game of Life with limited options.
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 5 Working with Images Starting Out with Games & Graphics in.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
tiled Map Case Study: Rendering with JPanel © Allan C. Milne v
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved. Chapter 7 The Game Loop and Animation Starting Out with Games & Graphics.
Advanced User Interfaces with Java SD’98 - Session 3206 Ted Faison Faison Computing Inc.
Graphics and Java 2D. 2 Introduction Java’s graphics capabilities –Drawing 2D shapes –Controlling colors –Controlling fonts Java 2D API –More sophisticated.
J McQuillan SE204: 2004/2005: Lecture 4slide 1 The Graphics Class Used when we need to draw to the screen Two graphics classes –Graphics –Graphics2D.
Graphics Copyright © 2015 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. Java Methods Object-Oriented Programming and Data.
Java Graphics. Review 3 kinds of elements in components API? Layout managers Events Extend vs. Implement.
Field Trip #19 Animations with Java By Keith Lynn.
-Sai Phalgun Tatavarthy. Outline What is a “Graphing Calculator”? Graphics, Graphics2D classes Methods of Graphics object Custom Painting The paintComponent()
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Introduction to Android (Part.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
(C) 2010 Pearson Education, Inc. All rights reserved.  Class Graphics (from package java.awt) provides various methods for drawing text and shapes onto.
Deliver Information, not Just Data Design displays carefully –Visual order and user focus (control contrast) –Match the medium (mixed metaphors) –Attention.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
Java Dynamic Graphics.
Graphics and Java2D Chapter Java Coordinate System Origin is in _____________ corner –Behind title bar of window X values increase to the ________.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Advanced Java Screen Update Techniques SD’98 - Session 4406 Ted Faison Faison Computing Inc.
Basic Graphics 03/03/16 & 03/07/16 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
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,
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Chapter 3 Syntax, Errors, and Debugging
Java Graphics CS 2511.
Graphics and Multimedia
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.
עקרונות תכנות מונחה עצמים תרגול 7: אנימציה
Presentation transcript:

More Java Drawing in 2D Animations with Timer

Drawing Review A simple two-dimensional coordinate system exists for each graphics context or drawing surface such as a JPanel Points on the coordinate system represent single pixels (no world coordinates exist) Top left corner of the area is coordinate A drawing surface has a width and height example: JPanel has getWidth() and getHeight() methods Anything drawn outside of that area is not visible You see no errors or exceptions either

JComponent To begin drawing we first need a class which extends JComponent. Use JPanel. Once we subclass JPanel we can override the paintComponent() method to specify what we want the panel to paint when repainting When painting we paint to a Graphics context (which is given to us as an argument to paintComponent )

4 Extend JPanel public class DrawingPanel extends JPanel { private Arc2D pieArc; public DrawingPanel() { pieArc = new Arc2D.Double(Arc2D.PIE); pieArc.setArc(20.0, 20.0, 33.0, 33.0, 15.0, 320.0, Arc2D.PIE); public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setPaint(Color.RED); g2.fill(pieArc); g2.drawLine(5, 80, 100, 80); } 4

paintComponent(Graphics g) paintComponent() is the method which is called when repainting a Component. It should never be called explicitly, but instead repaint() should be invoked which will then call paintComponent() on the appropriate Components When overriding paintComponent() the first line should be super.paintComponent(g) which will clear the panel for drawing

Graphics vs. Graphics2D We are passed a Graphics object to paintComponent() which we paint to Cast the object passed to a Graphics2D which has much more functionality. Graphics2D has more sophisticated control over geometry, coordinate transformations, color management, and text layout. This is the fundamental class for rendering 2-D shapes, text and images on the Java(tm) platform Why didn’t Java just pass Graphics2D? Legacy support

Using Java Geometry We've seen Rectangle Classes within java.awt.geom AffineTransform, Arc2D, Arc2D.Double, Arc2D.Float, Area, CubicCurve2D, CubicCurve2D.Double, CubicCurve2D.Float, Dimension2D, Ellipse2D,Ellipse2D.Double, Ellipse2D.Float, FlatteningPathIterator, GeneralPath, Line2D, Line2D.Double, Line2D.Float, Path2D, Path2D.Double, Path2D.Float, Point2D, Point2D.Double, Point2D.Float, QuadCurve2D, QuadCurve2D.Double, QuadCurve2D.Float, Rectangle2D, Rectangle2D.Double, Rectangle2D.Float, RectangularShape, RoundRectangle2D, RoundRectangle2D.Double, RoundRectangle2D.Float

Using Java Geometry (cont.) Note: Arc2D.Double means that Double is an inner class contained in Arc2D pieArc = new Arc2D.Double(Arc2D.PIE); pieArc.setArc(20.0, 20.0, 33.0, 33.0, 15.0, 320.0, Arc2D.PIE); The difference between g2.draw() and g2.fill() is that draw will draw an outline of the object while fill will fill in the object

Alpha (Transparency) We can assign transparency (alpha) values to drawing operations so that the underlying graphics partially shows through when you draw shapes or images. Create an AlphaComposite object using AlphaComposite.getInstance with a mixing rule There are 12 built-in mixing rules but we only care about AlphaComposite.SRC_OVER See AlphaComposite API for more details Alpha values range from 0.0f to 1.0f, completely transparent and completely opaque respectively Pass the AlphaComposite object to g2.setComposite() so that it will be used in our rendering

Alpha (Transparency, cont.) pieArc = new Arc2D.Double(Arc2D.PIE); pieArc.setArc(20.0, 20.0, 66.0, 66.0, 15.0, 320.0, Arc2D.PIE); pieArcRed = new Arc2D.Double(Arc2D.PIE); pieArcRed.setArc(35.0, 35.0, 66.0, 66.0, -15.0, 240, Arc2D.PIE); //.... g2.setPaint(Color.BLUE); g2.fill(pieArc); Composite originalComposite = g2.getComposite(); AlphaComposite alphaComposite = // 0.1f would make red faint AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f); g2.setComposite(alphaComposite); g2.setPaint(Color.RED); g2.fill(pieArcRed); g2.setComposite(originalComposite); // Run animation.DrawPanelMain

Animation with javax.swing.Timer At its simplest, animation is the time-based alteration of graphical objects through different states, locations, sizes and orientations This code set a timer to send an actionPerformed message to its listener(s) every 10 milliseconds timer = new javax.swing.Timer(10, new TimerListener()); timer.start(); The code in the actionPerformed message of class TimerListener that will be executed ever 10 ms public class TimerListener implements ActionListener { public void actionPerformed(ActionEvent evt) { // Executes every so many ms the Timer has been set to // from a separate thread that it created for itself } Advanced SwingF2-24

Animation: Simple Timer Example public class RedBallPanel extends JPanel { private static Random generator; private Ellipse2D pellet; private int tick; private int x, y; private Timer timer; public RedBallPanel() { generator = new Random(); startAnimating(); public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setPaint(Color.RED); g2.fill(pellet); } private void startAnimating() { pellet = new Ellipse2D.Double(); tick = 0; timer = new javax.swing.Timer(1000, new TimerListener()); timer.start(); } public class TimerListener implements ActionListener { public void actionPerformed( x = generator.nextInt(Main.FR.. y = generator.nextInt(Main.FR.. pellet.setFrame(x, y, 10, 10); repaint(); tick++; if (tick > 20) timer.stop(); } executes every 1000 ms

Animation: Double Buffering Double buffering is the mechanism of using a second bitmap (or buffer) which receives all of the updates to a window during an update. Once all of the objects of a window have been drawn, then the bitmap is copied to the primary bitmap seen on the screen. This prevents the flashing from appearing to the user that occurs when multiple items are being drawn to the screen.

Animation: Double Buffering In Swing Swing now (as of Java 6) provides true double buffering. Previously, application programmers had to implement double buffering themselves The no-arg constructor of JPanel returns a JPanel with a double buffer (and a flow layout) by default "...uses additional memory space to achieve fast, flicker-free updates."

Animation: Double Buffering In Swing Each box drawn in order might be detectable by user. The entire backing bitmap is copied at once to the visible bitmap, avoiding any flicker. Drawn 1st Drawn 2nd Drawn 3rd Drawn 4th Backing Bitmap (not visible to user) Window Bitmap (visible to user)

Animated GIF’s Using animated GIF’s in your projects is okay, but there is a better way to animate things Problems with animated GIF’s: The timings between frames are set in stone and cannot be controlled by the programmer. During the first animation of the GIF it will appear that your image is not loaded since the GIF loads each frame as it is displayed (looks ugly, but can be avoided using image loaders) Programmers also can’t control which frame to display or start/stop on since the GIF just keeps animating Instead of Animated GIF’s, most 2D games will use what is called a SpriteSheet and then animate using a Timer or Thread

Sprite Sheets A sprite sheet is a depiction of various sprites arranged in one image, detailing the exact frames of animation for each character or object by way of layout. The programmer can then control how fast frames switch and which frame to display. Additionally the whole sheet is loaded at once as a single image and won’t cause a loading glitch. In Java we can use the BufferedImage method: getSubimage(int x, int y, int w, int h) Returns a subimage defined by a specified rectangular region.