Chapter 5 Programming Graphics. Chapter Goals To be able to write applications with simple graphical user interfaces To display graphical shapes such.

Slides:



Advertisements
Similar presentations
Chapter 18 Building the user interface. This chapter discusses n Javas graphical user interface. n Swing: an enhancement of a library called the Abstract.
Advertisements

1 Event Listeners Some Events and Their Associated Event Listeners Act that Results in the EventListener Type User clicks a button, presses Enter while.
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.
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.
Graphical User Interfaces
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.
Graphics and event-driven programs Learning objectives By the end of this lecture you should be able to: identify and use some of the common components.
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.
Examples. // A simple Frame with Rectangle Inside import java.awt.*; import javax.swing.*; import java.awt.geom.*; // For Shapes class rectComponent extends.
Drawing in a frame – Java GUI
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?
Graphics Programming. Introduction GOAL: Build the Indexer Client Event-driven vs. Sequential programs Terminology – Top-level windows are called “frame.
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.
Chapter 4 (Horstmann’s Book) Interface Types and Polymorphism: Graphics, Timer, Animation Hwajung Lee.
Graphical User Interfaces, 2D Graphics & Game Programming.
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.
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.
1 Chapter 8 Objects and Classes Lecture 2 Prepared by Muhanad Alkhalisy.
Chapter 5 Ch 1 – Introduction to Computers and Java Defining Classes and Methods 1.
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.
Things to mention public static void main(String [] args) –The starting point for a free-standing Java application (i.e. one not run from the DrJava interactions.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Java Applets What is an Applet? How do you create.
Java Review Structure of a graphics program. Computer Graphics and User Interfaces Java is Object-Oriented A program uses objects to model the solution.
Drawing pictures with Java. JFrame: the basic Java window The swing package contains classes, objects and methods that can be used to create a consistent.
Java Concepts Chapter 2 – Graphical Applications Mr. Smith AP Computer Science A.
1 Interface Types & Polymorphism & introduction to graphics programming in Java.
1 Principles of Computer Science I Prof. Nadeem Abdul Hamid CSC 120 – Fall 2005 Lecture Unit 5 - Graphics.
Chapter 4: Applets and Graphics 1 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 4 Applets and Graphics.
Previous programs used a JLabel for OUTPUT. Another Swing component that can be used for both user input and output is the JTextfield. Suppose we want.
1 Block1 – unit 2 (The Case study in Budd 5-6).  create a small application that uses the Abstract Windowing Toolkit (AWT)  Swing packages to simulate.
Field Trip #19 Animations with Java By Keith Lynn.
Copyright © 2013 by John Wiley & Sons. All rights reserved. GRAPHICAL USER INTERFACES CHAPTER Slides by Donald W. Smith TechNeTrain.com Final Draft 10/30/11.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Chapter 12 1 TOPIC 13B l Buttons and Action Listeners Window Interfaces Using Swing Objects.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
(C) 2010 Pearson Education, Inc. All rights reserved.  Class Graphics (from package java.awt) provides various methods for drawing text and shapes onto.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
Fall 2006Adapted from Java Concepts Companion Slides1 Programming Graphics Advanced Programming ICOM 4015 Lecture 14 Reading: Java Concepts Chapter 5.
Review_6 AWT, Swing, ActionListener, and Graphics.
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.
Basics of GUI Programming Chapter 11 and Chapter 22.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Graphical User Interface (GUI) Two-Dimensional Graphical Shapes.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Basic Graphics 03/03/16 & 03/07/16 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
CPCS 391 Computer Graphics Lab One. Computer Graphics Using Java What is Computer Graphics: Computer graphics are graphics created using computers and,
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
Break Time! Graphical User Interface (GUI) NO EXAM….ONLY PROJECT!
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
10/20/2005week71 Graphics, mouse and mouse motion events, KeyEvent Agenda Classes in AWT for graphics Example java programs –Graphics –Mouse events –Mouse.
Chapter 5 Programming Graphics
A First Look at GUI Applications
Basic Graphics Chapter 5 3/19/15 Thursday Section Only
4.14 GUI and Graphics Case Study: Creating Simple Drawings (Cont.)
Presentation transcript:

Chapter 5 Programming Graphics

Chapter Goals To be able to write applications with simple graphical user interfaces To display graphical shapes such as lines and ellipses To use colors To display drawings consisting of many shapes To read input from a dialog box To develop test cases that validate the correctness of your programs

Agenda Basic user interface elements  JFrame  JPanel  Graphical shapes, lines etc. RectangleDemo revisited  ActionListener  JButton  LayoutManager Function Plotter

Frame Windows The JFrame class import javax.swing.*; JFrame frame = new JFrame(); frame.setSize(300, 400); frame.setTitle("An Empty Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true);

A Frame Window Figure 1: A Frame Window

File EmptyFrameViewer.java 01: import javax.swing.*; 02: 03: public class EmptyFrameViewer 04: { 05: public static void main(String[] args)‏ 06: { 07: JFrame frame = new JFrame(); 08: 09: final int FRAME_WIDTH = 300; 10: final int FRAME_HEIGHT = 400; 11: 12: frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); 13: frame.setTitle("An Empty Frame"); 14: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 15: 16: frame.setVisible(true); 17: } 18: }

Drawing Shapes paintComponent : called whenever the component needs to be repainted: If you use a JPanel instead of a JComponent, the method is called paint public class RectangleComponent extends JComponent { public void paintComponent(Graphics g) { // Recover Graphics2D Graphics2D g2 = (Graphics2D) g;... } }

Drawing Shapes Graphics class lets you manipulate the graphics state (such as current color) Graphics2D class has methods to draw shape objects Use a cast to recover the Graphics2D object from the Graphics parameter java.awt package Rectangle box = new Rectangle(5, 10, 20, 30); g2.draw(box);

RectangleDemoII  RectangleDemoII extends (is a) JPanel and can therefore be drawn upon  Out of main()!  Construct Rectangle objects  Allow the user to specify one Rectangle  Construct a JFrame  Set this “Jpanel” as the JFrame's contentPane  Make the frame visible public class RectangleDemoII extends JPanel {... frame.setContentPane(this); public static void main(String[] args) { RectangleDemoII me = new RectangleDemoII(); }

Drawing Rectangles Figure 2: Drawing Rectangles JPanel JFrame rect1, rect2,... JFrame draw()‏ Graphics2D

Graphical Shapes Rectangle, Ellipse2D.Double, and Line2D.Double describe graphical shapes We must construct objects and then have a Graphics object draw the shape Ellipse2D.Double ellipse = new Ellipse2D.Double( x, y, width, height); g2.draw(ellipse); import java.awt.geom.Ellipse2D; // no.Double

An Ellipse Figure 6: An Ellipse and Its Bounding Box

Drawing Lines To draw a line: or, Line2D.Double segment = new Line2D.Double(x1, y1, x2, y2); Point2D.Double from = new Point2D.Double(x1, y1); Point2D.Double to = new Point2D.Double(x2, y2); Line2D.Double segment = new Line2D.Double(from, to);

Drawing Strings Figure 7: Basepoint and Baseline g2.drawString("Message", 50, 100);

Colors Standard colors Color.BLUE, Color.RED, Color.PINK etc. Specify red, green, blue between 0.0F and 1.0F Color magenta = new Color(1.0F, 0.0F, 1.0F); // F = float Set color in graphics context Color is used when drawing and filling shapes g2.setColor(magenta); g2.fill(rectangle); // filled with current color

Drawing Complex Shapes Good practice: Make a class for each graphical shape Plan complex shapes by making sketches on graph paper class Car {... public void draw(Graphics2D g2) { // Drawing instructions... } }

Drawing Graphical Shapes Rectangle leftRectangle = new Rectangle(100, 100, 30, 60); Rectangle rightRectangle = new Rectangle(160, 100, 30, 60); Line2D.Double topLine = new Line2D.Double(130, 100, 160, 100); Line2D.Double bottomLine = new Line2D.Double(130, 160, 160, 160);

Reading numerical input NumericalInput allows easy input of up to five numerical (double) values int x, y, w, h; // x, y-coordinates, width and height NumericalInput ni = new NumericalInput( "x", "y", "width", "height"); while(!ni.isReady());// Wait for input x = (int) ni.getFirstInput(); // Obtain input y = (int) ni.getSecondInput(); w = (int) ni.getThirdInput(); h = (int) ni.getFourthInput(); rect3 = new Rectangle(x,y,w,h);

Reading numerical input Figure 13: An Input Dialog Box Upon receiving an event, the N.I. acquires all input values Click! NumericalInput Registered as ActionListener

PlotDemo Plots a parabola corresponding to a 2 nd order polynomial p(x) = a x^2 + b x + c PlotDemo: Class representing a 2 nd order polynomial PlotDemo: Main application – obtains user input via a NumericalInput object and starts the plotting FunctionPlotter: JFrame containing a PolynomialGraph as its contentPane, as well as an Exit-button Continued…

PlotDemo PolynomialGraph: JPanel handling all plotting in its paintComponent method:  It first draws a coordinate system  Then it uses a for loop to step through all x-coordinates and computes the corresponding y-values by invoking appropriate methods in the Polynomial object  Then it draws a line segment between the previous point and the current point Continued…

Classes (Objects) in PlotDemo JButton Click! Polynomial p(x)‏ FunctionPlotter (JFrame)‏ PolynomialGraph (JPanel)‏ NumericalInput paint()‏ coefficients

Summary Graphical user interfaces are important, but sometimes require a lot of work To draw custom shapes, you put the drawing code in the paint method in a Jpanel Other components, such as JButton, handle drawing by themselves Components must be added to a container If you want to be able to receive events, you must register ActionListeners with the event sources

Comparing Visual and Numerical Information Compute intersection between circle and vertical line Circle has radius r = 100 and center (a, b) = (100, 100) Line has constant x value Continued… Note: This and the following pages are not part of the lecture; it is purely included for reference purposes

Comparing Visual and Numerical Information Calculate intersection points using mathematics: Equation of a circle with radius r and center point (a, b) is If you know x, then you can solve for y:

Comparing Visual and Numerical Information That is easy to compute in Java: Plot circle, line, computed intersection points Visual and numerical results should be the same double root = Math.sqrt(r * r - (x - a) * (x - a)); double y1 = b + root; double y2 = b - root;

Intersection of a Line and a Circle Figure 15 Intersection of a Line and a Circle

File IntersectionComponent.java 01: import java.awt.Graphics; 02: import java.awt.Graphics2D; 03: import java.awt.geom.Ellipse2D; 04: import java.awt.geom.Line2D; 05: import javax.swing.JComponent; 06: 07: /** 08: A component that computes and draws the intersection points 09: of a circle and a line. 10: */ 11: public class IntersectionComponent extends JComponent 12: { 13: /** 14: Constructs the component from a given x-value for the line anX the x-value for the line (between 0 and 200)‏ 16: */ Continued…

File IntersectionComponent.java 17: public IntersectionComponent(double anX)‏ 18: { 19: x = anX; 20: } 21: 22: public void paintComponent(Graphics g)‏ 23: { 24: Graphics2D g2 = (Graphics2D) g; 25: 26: // Draw the circle 27: 28: final double RADIUS = 100; 29: 30: Ellipse2D.Double circle 31: = new Ellipse2D.Double(0, 0, 2 * RADIUS, 2 * RADIUS); 32: g2.draw(circle); 33: 34: // Draw the vertical line 35: Continued…

File IntersectionComponent.java 36: Line2D.Double line 37: = new Line2D.Double(x, 0, x, 2 * RADIUS); 38: g2.draw(line); 39: 40: // Compute the intersection points 41: 42: double a = RADIUS; 43: double b = RADIUS; 44: 45: double root = Math.sqrt(RADIUS * RADIUS - (x - * (x - a)); 46: double y1 = b + root; 47: double y2 = b - root; 48: 49: // Draw the intersection points 50: 51: LabeledPoint p1 = new LabeledPoint(x, y1); 52: LabeledPoint p2 = new LabeledPoint(x, y2); Continued…

File IntersectionComponent.java 53: 54: p1.draw(g2); 55: p2.draw(g2); 56: } 57: 58: private double x; 59: }

File IntersectionViewer.java 01: import javax.swing.JFrame; 02: import javax.swing.JOptionPane; 03: 04: public class IntersectionViewer 05: { 06: public static void main(String[] args)‏ 07: { 08: JFrame frame = new JFrame(); 09: 10: final int FRAME_WIDTH = 300; 11: final int FRAME_HEIGHT = 400; 12: 13: frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); 14: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 15: Continued…

File IntersectionViewer.java 16: String input = JOptionPane.showInputDialog("Enter x"); 17: double x = Double.parseDouble(input); 18: IntersectionComponent component 19: = new IntersectionComponent(x); 20: frame.add(component); 21: 22: frame.setVisible(true); 23: } 24: }

File LabeledPoint.java 01: import java.awt.Graphics2D; 02: import java.awt.geom.Ellipse2D; 03: 04: /** 05: A point with a label showing the point's coordinates. 06: */ 07: public class LabeledPoint 08: { 09: /** 10: Construct a labeled point. anX the x coordinate aY the y coordinate 13: */ 14: public LabeledPoint(double anX, double aY)‏ 15: { 16: x = anX; 17: y = aY; 18: } Continued…

File LabeledPoint.java 19: 20: /** 21: Draws the point as a small circle with a coordinate label. g2 the graphics context23: */ 24: public void draw(Graphics2D g2)‏ 25: { 26: // Draw a small circle centered around (x, y)‏ 27: 28: Ellipse2D.Double circle = new Ellipse2D.Double( 29: x - SMALL_CIRCLE_RADIUS, 30: y - SMALL_CIRCLE_RADIUS, 31: 2 * SMALL_CIRCLE_RADIUS, 32: 2 * SMALL_CIRCLE_RADIUS); 33: 34: g2.draw(circle); 35: 36: // Draw the label Continued…