1 / 45

Lecture 17 Programming Graphics

Lecture 17 Programming Graphics. Richard Gesick. Goals. To be able to write simple applications 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 . Frame Windows. The JFrame class

urbain
Download Presentation

Lecture 17 Programming Graphics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 17Programming Graphics Richard Gesick

  2. Goals • To be able to write simple applications • 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

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

  4. A Frame Window Figure 1:A Frame Window

  5. File EmptyFrameViewer.java import javax.swing.*; public class EmptyFrameViewer { public static void main(String[] args) { JFrame frame = new JFrame(); final int FRAME_WIDTH = 300; final int FRAME_HEIGHT = 400; frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setTitle("An Empty Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }

  6. Drawing Shapes • paintComponent: called whenever the component needs to be repainted: public class RectComponent extends JComponent{ public void paintComponent(Graphics g) { // Recover Graphics2D Graphics2D g2 = (Graphics2D) g; . . . }}

  7. 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 Rectangle box = new Rectangle(5, 10, 20, 30);g2.draw(box);

  8. Drawing Rectangles Figure 2:Drawing Rectangles

  9. Applets • Graphical Java programs • Run inside web browser • Platform-neutral • Easy deployment--loads when needed • Secure

  10. Web Browsers Accessing a Web Server

  11. HTML for Applets • Applets need class for applet code and size:<applet code="HamsterApplet.class"width="640" height="480">

  12. Viewing an Applet • Make one or more Java source files to implement your applet • One of the source files must define the applet class • Compile the source files into class files • Make an HTML file with the applet tag that references the applet class • Run appletviewer myapplet.html • Or load the HTML file into a Java 2 compliant browser

  13. The RectangleApplet in the Applet Viewer

  14. The RectangleApplet in a Browser

  15. Applets • Applets are programs that run inside a web browser . To implement an applet, use this code outline: public class MyApplet extends JApplet{ public void paint(Graphics g) { // Recover Graphics2D Graphics2D g2 = (Graphics2D) g; // Drawing instructions go here . . . }}

  16. Applets • You extendJApplet • You place the drawing code inside the paintmethod • To run an applet, you need an HTML file with the applet tag

  17. Applets • An HTML file can have multiple applets; add a separate applet tag for each applet • You view applets with the applet viewer or a Java enabled browser appletviewer RectangleApplet.html

  18. File RectangleApplet.java import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.JApplet; /** An applet that draws two rectangles. */ public class RectangleApplet extends JApplet { public void paint(Graphics g) { // Prepare for extended graphics Graphics2D g2 = (Graphics2D) g;

  19. File RectangleApplet.java // Construct a rectangle and draw it Rectangle box = new Rectangle(5, 10, 20, 30); g2.draw(box); // Move rectangle 15 units to the right and // 25 units down box.translate(15, 25); // Draw moved rectangle g2.draw(box); } }

  20. RectangleApplet.java (part 1) • The imported libraries import java.applet.Applet; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; /**    An applet that draws two rectangles. */

  21. RectangleApplet.java (part 2) public class RectangleApplet extends Applet {      public void paint(Graphics g)     {       Graphics2D g2 = (Graphics2D)g;           Rectangle cerealBox = new Rectangle(5, 10, 20, 30);        g2.draw(cerealBox);        cerealBox.translate(15, 25);          g2.draw(cerealBox);     } }

  22. RectangleApplet.html <applet code="RectangleApplet.class" width="300" height="400" > </applet>

  23. RectangleAppletExplained.html <html> <head> <title>Two rectangles</title> </head> <body> <p>Here is my <i>first applet</i>:</p> <applet code="RectangleApplet.class" width="300" height="400"> </applet> </body> </html>

  24. Applets Figure 3:An Applet in the Applet Viewer

  25. Applets Figure 4:An Applet in a Web Browser

  26. Graphical Shapes • Rectangle, Ellipse2D.Double,and Line2D.Double describe graphical shapes • We won't use the .Float classes • These classes are inner classes–doesn't matter to us except for the import statement: • Must construct and draw the shape import java.awt.geom.Ellipse2D; // no .Double Ellipse2D.Double ellipse = new Ellipse2D.Double (x, y, width, height);g2.draw(ellipse);

  27. An Ellipse Figure 6:An Ellipse and Its Bounding Box

  28. Drawing Lines • To draw a line:or, Line2D.Double s = 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);

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

  30. Give instructions to draw a circle with center (100, 100) and radius 25 Give instructions to draw a letter "V" by drawing two line segments Give instructions to draw a string consisting of the letter "V"

  31. Answers g2.draw(new Ellipse2D.Double(75, 75, 50, 50); Line2D.Double seg1 = new Line2D.Double(0, 0, 10, 30);g2.draw(segment1);Line2D.Double seg2 = new Line2D.Double(10, 30, 20, 0);g2.draw(segment2); g2.drawString("V", 0, 30);

  32. Colors Standard colors Color.BLUE,Color.RED,Color.PINK etc. Specify red, green, blue between 0.0F and 1.0F Colormagenta = newColor(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

  33. 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 . . . }}

  34. Drawing Cars Draw two cars: one in top-left corner of window, and another in the bottom right Compute bottom right position, inside paintmethod: getWidthand getHeight are applied to object that executes paint If window is resized paintis called and car position recomputed int x = getWidth() - 60;int y = getHeight() - 30;Car car2 = new Car(x, y);

  35. Drawing Cars Figure 8:The Car Component Draws Two Shapes

  36. Plan Complex Shapes on Graph Paper Figure 9:Using Graph Paper to Find Shape Coordinates

  37. Car.java import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.Ellipse2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; /** A car shape that can be positioned anywhere on the screen. */ public class Car { /** Constructs a car with a given top left corner @param x the x coordinate of the top left corner @param y the y coordinate of the top left corner */

  38. public Car(int x, int y) { xLeft = x; yTop = y; } /** Draws the car. @param g2 the graphics context */ public void draw(Graphics2D g2) { Rectangle body = new Rectangle(xLeft, yTop + 10, 60, 10); Ellipse2D.Double frontTire = new Ellipse2D.Double(xLeft + 10, yTop + 20, 10, 10); . . . .

  39. Extract from Car.java (1) public class Car {     /**        Constructs a car with a given top left corner        @param x the x coordinate of the top left corner       @param y the y coordinate of the top left corner    */  private double xLeft;  private double yTop; public Car(double x, double y)     {       xLeft = x;        yTop = y;     }

  40. Extract from Car.java (2) public void draw(Graphics2D g2)    {       Rectangle2D.Double body =  new Rectangle2D.Double(xLeft, yTop + 10, 60, 10); Ellipse2D.Double frontTire = new Ellipse2D.Double(xLeft + 10, yTop + 20, 10, 10); Ellipse2D.Double rearTire = new Ellipse2D.Double(xLeft + 40, yTop + 20, 10, 10); .... • Notice how each car now has its own set of starting coordinates that are entered by the user

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

  42. Reading Text Input A graphical application can obtain input by displaying a JOptionPane . The showInputDialog method displays a prompt and waits for user input . The showInputDialog method returns the string that the user typed String input = JOptionPane.showInputDialog("Enter x");double x = Double.parseDouble(input);

  43. Reading Text Input Figure 13:An Input Dialog Box

  44. Reading Text Input • If you put JOptionPane( ) in paint instead of the constructor or other applet functions, you will usually end up in an infinite loop because of the way the window manager interacts with paint().

  45. The Car applet • There are a couple of critical design points that need to be emphasized in the car applet. • In the program that drew 2 rectangles, those coordinates were "fixed" in the program and to change the position, we would have to modify the source code and recompile it before the positions would be changed. • In the author's car applet, observe how the cars are positioned.

More Related