1 / 48

Graphics in Java Applications

Graphics in Java Applications. The Graphics Class The Canvas Class The MouseListener Interface JavaDraw: A Demonstration of Graphics. Graphics in Java Applications. Can use turtle graphics for graphics, but very limited Turtle graphics screen is separate from rest of application

lafrance
Download Presentation

Graphics in Java Applications

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. Graphics in Java Applications The Graphics Class The Canvas Class The MouseListener Interface JavaDraw: A Demonstration of Graphics

  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(); • } • } Programming and Problem Solving With Java

More Related