Programming and Problem Solving With Java Copyright 1999, James M. Slack Graphics in Java...

48
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

Transcript of Programming and Problem Solving With Java Copyright 1999, James M. Slack Graphics in Java...

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

Programming and Problem SolvingWith Java

Copyright 1999, James M. Slack

Graphics in Java ApplicationsThe Graphics ClassThe Canvas ClassThe MouseListener InterfaceJavaDraw: A Demonstration of Graphics

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

Programming and Problem Solving With Java 2

Graphics in Java ApplicationsCan use turtle graphics for graphics, but very

limitedTurtle graphics screen is separate from rest of applicationUser must press Continuous button to start turtleNo text in turtle drawing area

Will see how to use the Graphics class to draw shapesLinesRectanglesOvals ...

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

Programming and Problem Solving With Java 3

The Graphics ClassDrawing 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 frameArgument to Frame.paint() is Graphics objectArgument represents the drawing area of the frame

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

Programming and Problem Solving With Java 4

The Graphics Class: TextUse Graphics.drawString() to put text in the

graphics drawing areaArguments

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 frame0,0 is in the title bar areaDon’t write in title bar area -- it won’t show

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

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(); }}

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

Programming and Problem Solving With Java 6

The Graphics Class: FontsCan change text attributes with setFont()setFont() argument:: a Font objectFont arguments

Name of installed fontFont style (Font.PLAIN, Font.ITALIC, Font.BOLD)Point size

Font myFont = new Font("TimesRoman", Font.ITALIC, 28);g.setFont(myFont);

Simpler approachg.setFont(new Font("TimesRoman", Font.ITALIC, 28));

Installed fonts on (nearly) any machineTimeRomanHelveticaCourier

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

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

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

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(); }}

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

Programming and Problem Solving With Java 9

The Graphics Class: ColorsUse Graphics.setColor() to set color of Graphics

object (before drawing it)Can use RBG colors to specify exact colorEasiest way: use predefined constants in Color class:

Exampleg.setColor(Color.blue);

black blue cyan darkGray gray

green lightGray magenta orange pink

red white yellow

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

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(); }}

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

Programming and Problem Solving With Java 11

The Graphics Class: LinesThe drawLine() method draws a line between two

pointsArguments

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, 70g.drawLine(50, 50, 100, 70);

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

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); }}

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

Programming and Problem Solving With Java 13

The Graphics Class: Linespublic class TestDrawLine{ public static void main(String[] args) { new DrawLineExample(); }}

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

Programming and Problem Solving With Java 14

The Graphics Class: RectanglesThe drawRect() method draws a rectangle between

two pointsArguments

x position of beginning of upper left corner y position of beginning of upper left cornerwidth of rectangleheight of rectangle

Orientation is fixed (can’t rotate 45 degrees, say)Example: draw rectangle with 50, 50 upper left

corner, width 100, height 70g.drawRect(50, 50, 100, 70);

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

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(); }}

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

Programming and Problem Solving With Java 16

The Graphics Class: PolygonsThe drawPolygon() method draws a closed polygon

SquareTriangleRectangleAny other closed shape (doesn’t need to be regular)

Argument: a Polygon objectExample

Polygon triangle = new Polygon();triangle.addPoint(20, 20);triangle.addPoint(50, 100);triangle.addPoint(80, 30);

Pass the Polygon object to drawPolygon() to draw itg.drawPolygon(triangle);

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

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(); }}

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

Programming and Problem Solving With Java 18

The Graphics Class: Other MethodsThe drawOval() method

x position of the upper left corner of the oval y position of the upper left corner of the ovalwidth of the ovalheight of the oval

The drawArc() methodSame arguments as drawOval() plusStarting angleNumber of degrees

Example of drawArc(): draw Cg.drawArc(20, 20, 100, 100, 90, 180);

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

Programming and Problem Solving With Java 19

The Graphics Class: Other Methods“Fill” versions of drawing methodsFills the open space with the current colorExamples

fillRect() fillOval() fillArc() fillPolygon()

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

Programming and Problem Solving With Java 20

The Canvas ClassCanvas covers just part of a Frame

Direct drawing to Canvas instead of FrameAllows restricted drawing (Like a Panel for GUI applications)

Each Canvas gets its own paint() methodpaint() method for a Canvas only applies to that Canvas

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

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); }}

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

Programming and Problem Solving With Java 22

The Canvas Classclass 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(); }}

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

Programming and Problem Solving With Java 23

The MouseListener InterfaceCan have program respond to mouse events in the

drawing area (not just for buttons and menus)MouseListener interface methods

mousePressed(): user pressed mouse button downmouseReleased(): user released mouse buttonmouseClicked(): user pressed and released mouse

button without moving itmouseEntered(): user moved mouse into drawing areamouseExited(): user moved mouse out of drawing area

Argument for each method is MouseEvent objectgetPoint() method returns mouse location as Point object

with public x and y variables

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

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(); }

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

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()); }

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

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(); }}

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

Programming and Problem Solving With Java 27

The MouseListener Interface1. Mouse enterswindow

2. Click mouse (pressand release)

3. Press mousebutton and hold

4. Release mousebutton

5. Mouse exitswindow

1: Mouse entered at java.awt.Point[x=193,y=80]2: Mouse pressed at java.awt.Point[x=41,y=59]

Mouse released at java.awt.Point[x=41,y=59]Mouse clicked at java.awt.Point[x=41,y=59]

3: Mouse pressed at java.awt.Point[x=46,y=158]4: Mouse released at java.awt.Point[x=167,y=152]5: Mouse exited at java.awt.Point[x=204,y=107]

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

Programming and Problem Solving With Java 28

The MouseListener InterfaceAnother example of MouseListener: Draw a line

between mouse clicksSteps

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

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

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(); }

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

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) {}

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

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(); }}

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

Programming and Problem Solving With Java 32

The MouseListener InterfaceSystem will use paint() automatically when window

is uncovered or resizedProgram should use repaint() method to redraw

Calls paint() to redraw drawing areaUse 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

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

Programming and Problem Solving With Java 33

JavaDraw Demonstration

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

Programming and Problem Solving With Java 34

JavaDraw DemonstrationFeatures

User can draw lines, rectangles, ovals with mouseUser clicks at starting point, then releases at ending pointUser can clear the drawing areaUser can undo actions, all the way to a blank drawing

areaDemonstrates

Drawing shapesCanvasBorder layout

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

Programming and Problem Solving With Java 35

JavaDraw DemonstrationDesign of JavaDraw

JavaDraw

main()

DrawFrame

actionPerformed()

Line

draw()

Oval

draw()

DrawCanvas

setShape()clear()undo()mousePressed()mouseReleased()paint()

Shape

draw()

Rectangle

draw()

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

Programming and Problem Solving With Java 36

JavaDraw DemonstrationShape is abstract, with Line, Rectangle, and Oval

subclassesAllows easy storage of these subclasses in a VectorPolymorphism: Vector (and supporting code) only deal

with Shape objects

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

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);}

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

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;}

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

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;}

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

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;}

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

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; }

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

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(); }

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

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(); }

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

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();

}

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

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());

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

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(); }

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

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); } }}

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

Programming and Problem Solving With Java 48

JavaDraw Demonstration// ----------- JavaDraw class ----------------------------------

public class JavaDraw{ public static void main(String[] args) { new DrawFrame(); }}