Programming and Problem Solving With Java Copyright 1999, James M. Slack Graphics in Java Applications The Graphics Class The Canvas Class The MouseListener.

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

Made with love, by Zachary Langley Applets The Graphics Presentation.
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?
Java Graphics Section 1 - Multi-File Graphics Programs Section 2 - The Coordinate System and Graphics Context g Section 3 - The Java Drawing and Painting.
Computer Science 209 Graphics and GUIs. Working with Color The class java.awt.Color includes constants for typical color values and also supports the.
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 With Applets Feb 23, Applets There are three different types of executable java code. –Standalone application, which has main()
Mouse Events and Keyboard Events
1 Chapter 15 l Basic Figures l Colors l Fonts and Other Text Details Graphics Objects.
Event Handling Events and Listeners Timers and Animation.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Topics  Applets  Classes used for graphics Graphics Point Dimension.
Copyright 2006 by Pearson Education 1 Building Java Programs Supplement 3G: Graphics.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Java Graphics Applets.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Applets and Graphics.
Graphics. Graphics Features in Java Topics to be covered Topics to be covered Graphics Basics Graphics Basics Coordinate System Coordinate System Graphics,
Mouse Events. Handling Mouse Events Java provides two listener interfaces to handle mouse events: MouseListener;  MouseListener;  MouseMotionListener.
Java applet basics, loading & displaying images After this section, you should be able to : –Use the applet tag and applet parameters –Describe what a.
Abstract Window Toolkit (AWT) The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI) programming. AWT features include:  A rich set.
Cs884(Prasad)java12AWT1 Abstract Windowing Toolkit Support for Graphical User Interface (Event-driven programming)
Java GUI’s are event driven, meaning they generate events when the user interacts with the program. Typical events are moving the mouse, clicking a mouse.
Graphics and Java 2D. 2 Introduction Java’s graphics capabilities –Drawing 2D shapes –Controlling colors –Controlling fonts Java 2D API –More sophisticated.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
SD2071 Games Programming Abstraction, inheritance and interfaces Exceptions Two dimensional arrays Java collections framework Files Aaron Kans.
Chapter 15Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 15 l Basic Figures l Colors l Fonts and Other Text Details.
Chapter 7 Graphics. © Daly and Wrigley Objectives Use Graphic Components: ▫ Strings ▫ Lines ▫ Rectangles ▫ Ovals ▫ Arcs Change the color and font of elements.
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 & Java 2D Drawing Two Dimensional Shapes Controlling Fonts Controlling Colors.
Canvas and Graphics CS 21a. 9/26/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L17: Canvas.
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.
7/3/00SEM107- © Kamin & ReddyClass 11 - Events - 1 Class 11 - Events r A couple of odds & ends m Component sizes  switch statement r Event types r Catching.
Graphics Copyright © 2015 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. Java Methods Object-Oriented Programming and Data.
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.
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.
Copyright © 2002, Systems and Computer Engineering, Carleton University b-Gui2.ppt * Object-Oriented Software Development Part 18-b Building.
MSc Workshop - © S. Kamin, U.Reddy Lect 4 - Events - 1 Lecture 4 – Event Handling r Painting r Event types r Catching different event types.
© 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.
Merete S COLLEGEFACULTY OF ENGINEERING & SCIENCE Graphics ikt403 – Object-Oriented Software Development.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
Chapter 2: Graphics In Java Basics of classes –instance variables –methods –overriding methods Graphics class (drawing routines) Other classes –Color –Font.
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
Mouse Listeners Moving the mouse will also generate events like the Timer –To have your program respond, you must implement either or both of MouseListener.
1 Graphics, Fonts and Color Chapter 9. 2 What is in this chapter: l Graphics class and coordinates l graphics primitives (lines,rectangles,ovals and arcs)
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.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 27.1 Test-Driving the Drawing Shapes Application.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 10.
GUI Tutorial Day 4. More GUI action  adding a Mouse Listener  SimpleDots  Simple mouse listener  Draw an oval where the mouse is clicked  Box example.
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,
Graphics JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
GUI Programming in Java Hao Jiang Boston College April, 2009.
©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.
Java Applets.
Object-Orientated Analysis, Design and Programming
Chapter 8 Graphics.
Graphics Chapter 6 Copyright © 2000 W. W. Norton & Company.
Computer Science 209 Graphics and GUIs.
Basic Graphics Chapter 5 3/19/15 Thursday Section Only
Chapter 10 Graphics.
4.14 GUI and Graphics Case Study: Creating Simple Drawings (Cont.)
Java Applets.
Chapter 8 Graphics.
Presentation transcript:

Programming and Problem Solving With Java Copyright 1999, James M. Slack Graphics in Java Applications The Graphics Class The Canvas Class The MouseListener Interface JavaDraw: A Demonstration of Graphics

Programming and Problem Solving With Java 2 Graphics in Java Applications  Can use turtle graphics for graphics, but very limited  Turtle graphics screen is separate from rest of application  User must press Continuous button to start turtle  No text in turtle drawing area  Will see how to use the Graphics class to draw shapes  Lines  Rectangles  Ovals ...

Programming and Problem Solving With Java 3 The Graphics Class  Drawing directly on a frame is easiest approach  Later, will see how to draw on portion of a frame (canvas)  Use paint() method in Frame class to put graphical elements on the frame  Argument to Frame.paint() is Graphics object  Argument represents the drawing area of the frame

Programming and Problem Solving With Java 4 The Graphics Class: Text  Use Graphics.drawString() to put text in the graphics drawing area  Arguments  Text to display (as a string)  x (horizontal) position of the beginning of the text, in pixels  y (vertical) position of the beginning of the text, in pixels  0,0 in upper left corner of frame  0,0 is in the title bar area  Don’t write in title bar area -- it won’t show

Programming and Problem Solving With Java 5 The Graphics Class: Text // Displays the string, "Hello!" at position 60, 80 of the frame. import java.awt.*; class DrawStringExample extends Frame { // Constructor public DrawStringExample() { // Call the constructor for the Frame class with the title // for the window super("Test drawString()"); // Set the size for the frame and display it setSize(300, 300); show(); } // paint: Display "Hello" public void paint(Graphics g) { g.drawString("Hello!", 60, 80); } public class TestDrawString { public static void main(String[] args) { new DrawStringExample(); }

Programming and Problem Solving With Java 6 The Graphics Class: Fonts  Can change text attributes with setFont()  setFont() argument:: a Font object  Font arguments  Name of installed font  Font style (Font.PLAIN, Font.ITALIC, Font.BOLD)  Point size Font myFont = new Font("TimesRoman", Font.ITALIC, 28); g.setFont(myFont);  Simpler approach g.setFont(new Font("TimesRoman", Font.ITALIC, 28));  Installed fonts on (nearly) any machine  TimeRoman  Helvetica  Courier

Programming and Problem Solving With Java 7 The Graphics Class: Fonts // Demonstrates how to use fonts import java.awt.*; class FontsExample extends Frame { // Constructor public FontsExample() { // Call the constructor for the Frame // class with the title for the window super("Test Fonts"); // Set the size for the frame and display it setSize(400, 250); show(); } // paint: Display different fonts and styles public void paint(Graphics g) { g.setFont(new Font("TimesRoman", Font.ITALIC, 28)); g.drawString("Some Examples of Fonts", 20, 45); g.setFont(new Font("Helvetica", Font.PLAIN, 12)); g.drawString("This is an example of plain 12pt Helvetica font", 20, 70); g.setFont(new Font("TimesRoman", Font.PLAIN, 12)); g.drawString("This is an example of plain 12pt TimesRoman font", 20, 90);

Programming and Problem Solving With Java 8 The Graphics Class g.setFont(new Font("Courier", Font.PLAIN, 12)); g.drawString("This is an example of plain 12pt Courier font", 20, 110); g.setFont(new Font("Helvetica", Font.ITALIC, 12)); g.drawString("This is an example of italic 12pt Helvetica font", 20, 130); g.setFont(new Font("TimesRoman", Font.ITALIC, 12)); g.drawString("This is an example of italic 12pt TimesRoman font", 20, 150); g.setFont(new Font("Courier", Font.ITALIC, 12)); g.drawString("This is an example of italic 12pt Courier font”, 20, 170); g.setFont(new Font("Helvetica", Font.BOLD, 12)); g.drawString("This is an example of bold 12pt Helvetica font", 20, 190); g.setFont(new Font("TimesRoman", Font.BOLD, 12)); g.drawString("This is an example of bold 12pt TimesRoman font", 20, 210); g.setFont(new Font("Courier", Font.BOLD, 12)); g.drawString("This is an example of bold 12pt Courier font", 20, 230); } public class TestFonts { public static void main(String[] args) { new FontsExample(); }

Programming and Problem Solving With Java 9 The Graphics Class: Colors  Use Graphics.setColor() to set color of Graphics object (before drawing it)  Can use RBG colors to specify exact color  Easiest way: use predefined constants in Color class:  Example g.setColor(Color.blue);

Programming and Problem Solving With Java 10 The Graphics Class: Colors // Demonstration of how to use colors import java.awt.*; class ColorsExample extends Frame { // Constructor public ColorsExample() { // Call the constructor for the Frame class with the title // for the window super("Test Colors"); // Set the size for the frame and display it setSize(200, 100); show(); } // paint: Display text with different colors public void paint(Graphics g) { g.setColor(Color.red); g.drawString("This is red", 20, 40); g.setColor(Color.green); g.drawString("This is green", 20, 60); g.setColor(Color.blue); g.drawString("This is blue", 20, 80); } public static void main(String[] args) { new ColorsExample(); }

Programming and Problem Solving With Java 11 The Graphics Class: Lines  The drawLine() method draws a line between two points  Arguments  x position of beginning of line  y position of beginning of line  x position of end of line  y position of end of line  Example: draw line from 50, 50 to 100, 70 g.drawLine(50, 50, 100, 70);

Programming and Problem Solving With Java 12 The Graphics Class: Lines // Demonstration of the drawLine() method import java.awt.*; class DrawLineExample extends Frame { // Constructor public DrawLineExample() { // Call the constructor for the Frame class with the title // for the window super("Test Drawing Lines"); // Set the size for the frame and display it setSize(200, 200); show(); } // paint: Display a square with an X inside public void paint(Graphics g) { g.drawLine(40, 40, 40, 160); g.drawLine(40, 160, 160, 160); g.drawLine(160, 160, 160, 40); g.drawLine(160, 40, 40, 40); g.drawLine(40, 40, 160, 160); g.drawLine(40, 160, 160, 40); }

Programming and Problem Solving With Java 13 The Graphics Class: Lines public class TestDrawLine { public static void main(String[] args) { new DrawLineExample(); }

Programming and Problem Solving With Java 14 The Graphics Class: Rectangles  The drawRect() method draws a rectangle between two points  Arguments  x position of beginning of upper left corner  y position of beginning of upper left corner  width of rectangle  height of rectangle  Orientation is fixed (can’t rotate 45 degrees, say)  Example: draw rectangle with 50, 50 upper left corner, width 100, height 70 g.drawRect(50, 50, 100, 70);

Programming and Problem Solving With Java 15 The Graphics Class: Rectangles // Demonstration of the drawRect() method import java.awt.*; class DrawRectanglesExample extends Frame { // Constructor public DrawRectanglesExample() { // Call the constructor for the Frame class with the title // for the window super("Test Drawing Rectangles"); // Set the size for the frame and display it setSize(200, 200); show(); } // paint: Display overlapping rectangles public void paint(Graphics g) { g.drawRect(40, 40, 100, 30); g.drawRect(50, 60, 120, 70); } public class TestDrawRectangle { public static void main(String[] args) { new DrawRectanglesExample(); }

Programming and Problem Solving With Java 16 The Graphics Class: Polygons  The drawPolygon() method draws a closed polygon  Square  Triangle  Rectangle  Any other closed shape (doesn’t need to be regular)  Argument: a Polygon object  Example Polygon triangle = new Polygon(); triangle.addPoint(20, 20); triangle.addPoint(50, 100); triangle.addPoint(80, 30);  Pass the Polygon object to drawPolygon() to draw it g.drawPolygon(triangle);

Programming and Problem Solving With Java 17 The Graphics Class: Polygons // Demonstration of drawPolygon() import java.awt.*; class DrawPolygonExample extends Frame { // Constructor public DrawPolygonExample() { // Call the constructor for the Frame class with the title // for the window super("Test Drawing Polygon"); // Set the size for the frame and display it setSize(250, 200); show(); } // paint: Build and display a polygon public void paint(Graphics g) { Polygon poly = new Polygon(); poly.addPoint(20, 60); poly.addPoint(60, 40); poly.addPoint(120, 60); poly.addPoint(180, 140); poly.addPoint(50, 160); g.drawPolygon(poly); } public class TestDrawPolygon { public static void main(String[] args) { new DrawPolygonExample(); }

Programming and Problem Solving With Java 18 The Graphics Class: Other Methods  The drawOval() method  x position of the upper left corner of the oval  y position of the upper left corner of the oval  width of the oval  height of the oval  The drawArc() method  Same arguments as drawOval() plus  Starting angle  Number of degrees  Example of drawArc(): draw C g.drawArc(20, 20, 100, 100, 90, 180);

Programming and Problem Solving With Java 19 The Graphics Class: Other Methods  “Fill” versions of drawing methods  Fills the open space with the current color  Examples  fillRect()  fillOval()  fillArc()  fillPolygon()

Programming and Problem Solving With Java 20 The Canvas Class  Canvas covers just part of a Frame  Direct drawing to Canvas instead of Frame  Allows restricted drawing  (Like a Panel for GUI applications)  Each Canvas gets its own paint() method  paint() method for a Canvas only applies to that Canvas

Programming and Problem Solving With Java 21 The Canvas Class // Demonstrates the use of Canvas objects import java.awt.*; class OvalCanvas extends Canvas { // paint: Draw a light gray filled oval public void paint(Graphics g) { g.setColor(Color.lightGray); g.fillOval(20, 20, 200, 100); } class RectangleCanvas extends Canvas { // paint: Draw a dark gray filled rectangle public void paint(Graphics g) { g.setColor(Color.darkGray); g.fillRect(30, 10, 50, 120); }

Programming and Problem Solving With Java 22 The Canvas Class class DrawCanvasExample extends Frame { // Constructor public DrawCanvasExample() { // Call the constructor for the Frame class with the title // for the window super("Test Canvas"); // Choose the layout manager and initialize it setLayout(new GridLayout(1, 2)); // Add components to frame add(new OvalCanvas()); add(new RectangleCanvas()); // Set the size for the frame and display it setSize(500, 200); show(); } public class TestCanvas { public static void main(String[] args) { new DrawCanvasExample(); }

Programming and Problem Solving With Java 23 The MouseListener Interface  Can have program respond to mouse events in the drawing area (not just for buttons and menus)  MouseListener interface methods  mousePressed(): user pressed mouse button down  mouseReleased(): user released mouse button  mouseClicked(): user pressed and released mouse button without moving it  mouseEntered(): user moved mouse into drawing area  mouseExited(): user moved mouse out of drawing area  Argument for each method is MouseEvent object  getPoint() method returns mouse location as Point object with public x and y variables

Programming and Problem Solving With Java 24 The MouseListener Interface // Demonstration of mouse events import java.awt.*; import java.awt.event.*; import java.util.Vector; class MouseListenerExample extends Frame implements MouseListener { public MouseListenerExample() { super("Test MouseListener"); // Choose the layout manager and initialize it setLayout(new BorderLayout()); // Add listener for mouse addMouseListener(this); // Set the size for the frame and display it setSize(200, 200); show(); }

Programming and Problem Solving With Java 25 The MouseListener Interface // mousePressed: Display the screen location at which the // user pressed the mouse button public void mousePressed(MouseEvent event) { System.out.println("Mouse pressed at " + event.getPoint()); } // mouseReleased: Display the screen location at which the // user released the mouse button public void mouseReleased(MouseEvent event) { System.out.println("Mouse released at " + event.getPoint()); } // mouseClicked: Display the screen location at which the // user clicked (pressed and released) the // mouse button public void mouseClicked(MouseEvent event) { System.out.println("Mouse clicked at " + event.getPoint()); }

Programming and Problem Solving With Java 26 The MouseListener Interface // mouseEntered: Display the screen location at which the // user moved the mouse into the frame public void mouseEntered(MouseEvent event) { System.out.println("Mouse entered at " + event.getPoint()); } // mouseExited: Display the screen location at which the // user moved the mouse out of the frame public void mouseExited(MouseEvent event) { System.out.println("Mouse exited at " + event.getPoint()); } public class TestMouseListener { public static void main(String[] args) { new MouseListenerExample(); }

Programming and Problem Solving With Java 27 The MouseListener Interface

Programming and Problem Solving With Java 28 The MouseListener Interface  Another example of MouseListener: Draw a line between mouse clicks  Steps  In mousePressed(), get location of mouse with getPoint(). Save location in instance variable beginPoint  In mouseReleased(), get location of mouse with getPoint(). Save location in instance variable endPoint Call repaint(), which calls paint() to redraw drawing area  In paint(), use drawLine() to draw line between beginPoint and endPoint

Programming and Problem Solving With Java 29 The MouseListener Interface // This program shows how to use mouse events to // control where lines are drawn on the frame. When the user // clicks the mouse button down, drags the mouse, and releases // the button, the program draws a line between those two points. // The frame will only display one line at a time. import java.awt.*; import java.awt.event.*; class LineDrawFrame extends Frame implements MouseListener { // Constructor public LineDrawFrame() { super("Test MouseListener with Lines"); // Choose the layout manager and initialize it setLayout(new BorderLayout()); // Add listener for mouse addMouseListener(this); // Set the size for the frame and display it setSize(300, 200); show(); }

Programming and Problem Solving With Java 30 The MouseListener Interface // mousePressed: When the user presses the mouse button, // store the point of the click (this is the // beginning point of the line) public void mousePressed(MouseEvent event) { beginPoint = event.getPoint(); } // mouseReleased: When the user releases the mouse button, // use the mouse's position as the end of the // line, then draw the line with the repaint() // method public void mouseReleased(MouseEvent event) { endPoint = event.getPoint(); repaint(); } // Unused MouseListener methods (but they must be defined in // the program) public void mouseEntered(MouseEvent event) {} public void mouseClicked(MouseEvent event) {} public void mouseExited(MouseEvent event) {}

Programming and Problem Solving With Java 31 The MouseListener Interface // paint: Draw a line between beginPoint and endPoint public void paint(Graphics g) { g.drawLine(beginPoint.x, beginPoint.y, endPoint.x, endPoint.y); } // Variables Point beginPoint, endPoint; } public class LineDraw { public static void main(String[] args) { new LineDrawFrame(); }

Programming and Problem Solving With Java 32 The MouseListener Interface  System will use paint() automatically when window is uncovered or resized  Program should use repaint() method to redraw  Calls paint() to redraw drawing area  Use whenever you want the system to use paint()  Don’t call paint() directly -- only run-time system should call paint()  Use repaint() when you know the drawing area needs to be updated, and run-time system won’t know this otherwise

Programming and Problem Solving With Java 33 JavaDraw Demonstration

Programming and Problem Solving With Java 34 JavaDraw Demonstration  Features  User can draw lines, rectangles, ovals with mouse  User clicks at starting point, then releases at ending point  User can clear the drawing area  User can undo actions, all the way to a blank drawing area  Demonstrates  Drawing shapes  Canvas  Border layout

Programming and Problem Solving With Java 35 JavaDraw Demonstration  Design of JavaDraw

Programming and Problem Solving With Java 36 JavaDraw Demonstration  Shape is abstract, with Line, Rectangle, and Oval subclasses  Allows easy storage of these subclasses in a Vector  Polymorphism: Vector (and supporting code) only deal with Shape objects

Programming and Problem Solving With Java 37 JavaDraw Demonstration // This program is a simple drawing program. It // allows the user to draw lines, rectangles, and ovals. The user // can select the next shape to be drawn from a toolbar on the // left side of the window. // There are no editing or file handling features in this // program. // // The program demonstrates the use of graphics in a Java // program, and also shows how to handle mouse click events. import java.awt.*; import java.awt.event.*; import java.util.Vector; // Shape class abstract class Shape { // draw: Draw the shape using the Graphics object g abstract public void draw(Graphics g); }

Programming and Problem Solving With Java 38 JavaDraw Demonstration // Line class class Line extends Shape { // Constructor public Line(Point beginPoint, Point endPoint) { beginPoint = beginPoint; endPoint = endPoint; } // draw: Draw the line using the Graphics object g public void draw(Graphics g) { g.drawLine(beginPoint.x, beginPoint.y, endPoint.x, endPoint.y); } // Variables Point beginPoint, endPoint; }

Programming and Problem Solving With Java 39 JavaDraw Demonstration // Rectangle class class Rectangle extends Shape { // Constructor public Rectangle(Point firstPoint, Point secondPoint) { upperLeftCorner = new Point(Math.min(firstPoint.x, secondPoint.x), Math.min(firstPoint.y, secondPoint.y)); width = Math.abs(firstPoint.x - secondPoint.x); height = Math.abs(firstPoint.y - secondPoint.y); } // draw: Draw the rectangle using the Graphics object g public void draw(Graphics g) { g.drawRect(upperLeftCorner.x, upperLeftCorner.y, width, height); } // Variables Point upperLeftCorner; int width, height; }

Programming and Problem Solving With Java 40 JavaDraw Demonstration // Oval class class Oval extends Shape { // Constructor public Oval(Point firstPoint, Point secondPoint) { upperLeftCorner = new Point(Math.min(firstPoint.x, secondPoint.x), Math.min(firstPoint.y, secondPoint.y)); width = Math.abs(firstPoint.x - secondPoint.x); height = Math.abs(firstPoint.y - secondPoint.y); } // draw: Draw the oval using the Graphics object g public void draw(Graphics g) { g.drawOval(upperLeftCorner.x, upperLeftCorner.y, width, height); } // Variables Point upperLeftCorner; int width, height; }

Programming and Problem Solving With Java 41 JavaDraw Demonstration // DrawCanvas class class DrawCanvas extends Canvas implements MouseListener { // Public constants public static final int SHAPE_LINE = 1; public static final int SHAPE_RECTANGLE = 2; public static final int SHAPE_OVAL = 3; // Constructor public DrawCanvas() { // Add listener for mouse addMouseListener(this); } // setShape: Change the shape of the next object to be drawn // on the canvas to the given shape public void setShape(int shape) { currentShape = shape; }

Programming and Problem Solving With Java 42 JavaDraw Demonstration // clear: Erase the canvas public void clear() { shapeVector.removeAllElements(); repaint(); } // undo: Remove the last-added shape (can be done any number // of times public void undo() { if (shapeVector.size() > 0) { shapeVector.setSize(shapeVector.size() - 1); repaint(); } // mousePressed: When the user presses the mouse button, // store the point of the click (this is the // first sizing point of the new shape) public void mousePressed(MouseEvent event) { beginPoint = event.getPoint(); }

Programming and Problem Solving With Java 43 JavaDraw Demonstration // mouseReleased: When the user releases the mouse button, // use the mouse's position as the second // sizing point (get the first sizing point from // the beginPoint variable set in the // mousePressed() method). Add the new shape // to the vector of shapes, handy repaint the // canvas. public void mouseReleased(MouseEvent event) { switch (currentShape) { case SHAPE_LINE: shapeVector.addElement(new Line(beginPoint, event.getPoint())); break; case SHAPE_RECTANGLE: shapeVector.addElement(new Rectangle(beginPoint, event.getPoint())); break; case SHAPE_OVAL: shapeVector.addElement(new Oval(beginPoint, event.getPoint())); } repaint(); }

Programming and Problem Solving With Java 44 JavaDraw Demonstration // Unused MouseListener methods (but they must be defined in // the program) public void mouseEntered(MouseEvent event) {} public void mouseClicked(MouseEvent event) {} public void mouseExited(MouseEvent event) {} // paint: Go through the vector of shapes and draw each one // on the canvas public void paint(Graphics g) { for (int i = 0; i < shapeVector.size(); i++) { ((Shape) shapeVector.elementAt(i)).draw(g); } // Variables Point beginPoint; int currentShape = SHAPE_LINE; // Default is to draw lines Vector shapeVector = new Vector(); }

Programming and Problem Solving With Java 45 JavaDraw Demonstration // DrawFrame class class DrawFrame extends Frame implements ActionListener { // Interface variables Button lineButton = new Button("Line"); Button rectangleButton = new Button("Rectangle"); Button circleButton = new Button("Oval"); Button clearButton = new Button("Clear"); Button undoButton = new Button("Undo"); Button exitButton = new Button("Exit"); DrawCanvas myDrawCanvas = new DrawCanvas(); // Constructor public DrawFrame() { // Call the constructor for the Frame class with the title // for the window super("Java Draw"); // Choose the layout manager and initialize it setLayout(new BorderLayout());

Programming and Problem Solving With Java 46 JavaDraw Demonstration // Make a "toolbar" panel out of the buttons Panel toolbarPanel = new Panel(); toolbarPanel.setLayout(new GridLayout(6, 1)); toolbarPanel.add(lineButton); toolbarPanel.add(rectangleButton); toolbarPanel.add(circleButton); toolbarPanel.add(clearButton); toolbarPanel.add(undoButton); toolbarPanel.add(exitButton); // Add listener for buttons lineButton.addActionListener(this); rectangleButton.addActionListener(this); circleButton.addActionListener(this); clearButton.addActionListener(this); undoButton.addActionListener(this); exitButton.addActionListener(this); // Add components to frame add(toolbarPanel, BorderLayout.WEST); add(myDrawCanvas, BorderLayout.CENTER); // Set the size for the frame and display it setSize(300, 300); show(); }

Programming and Problem Solving With Java 47 JavaDraw Demonstration // actionPerformed: Set the shape in the myDrawCanvas object // to the shape chosen by the user public void actionPerformed(ActionEvent event) { if (event.getSource() == lineButton) { myDrawCanvas.setShape(DrawCanvas.SHAPE_LINE); } else if (event.getSource() == rectangleButton) { myDrawCanvas.setShape(DrawCanvas.SHAPE_RECTANGLE); } else if (event.getSource() == circleButton) { myDrawCanvas.setShape(DrawCanvas.SHAPE_OVAL); } else if (event.getSource() == clearButton) { myDrawCanvas.clear(); } else if (event.getSource() == undoButton) { myDrawCanvas.undo(); } else if (event.getSource() == exitButton) { setVisible(false); dispose(); System.exit(0); }

Programming and Problem Solving With Java 48 JavaDraw Demonstration // JavaDraw class public class JavaDraw { public static void main(String[] args) { new DrawFrame(); }