7. Graphics and Review for Midterm

What We Will Cover


Illuminations

Questions on Completed Assignments?

7.1: Graphics Capabilities

Objectives

At the end of the lesson the student will be able to:

  • Control Java's graphics coordinates
  • Set colors and fonts
  • Draw strings in a graphics context

7.1.1: About Java's Graphics Capabilities

  • One of the early appeals of Java was its graphics capabilities
  • Could draw two-dimensional (2D) shapes in Applets
  • We will learn how to draw basic figures such as lines, ovals, and rectangles.
  • Basic figures can be combined to create elaborate pictures
  • Java’s graphics capabilities include:
    • Drawing 2D shapes
    • Controlling colors
    • Controlling fonts
  • Java 2D API adds more sophisticated graphics capabilities
    • Drawing custom 2D shapes
    • Filling shapes with colors and patterns

7.1.2: Java Coordinate System

  • Coordinates are a scheme for identifying all points on screen
  • Measured in pixels from the upper-left corner of screen
  • Any single point has an x-coordinate and y-coordinate
  • Coordinates are usually positive numbers

7.1.3: Graphics Contexts and Graphics Objects

  • Graphics context enables drawing on screen
  • Graphics object manages graphics context
  • Contains methods used to draw basic shapes and lines
  • Controls how information is drawn
  • Class Graphics is abstract and cannot be instantiated
  • Base class for all graphics contexts that allow an application to draw onto components
  • Class Component has a paint method which takes a Graphics object
  • public void paint(Graphics g)
  • paint method draws the component on the screen
  • Override paint method to draw figures such as lines, ovals and rectangles
  • paint method is called automatically
    • Should not be invoked in the programmer’s code.
    • To schedule paint, call method repaint

About JFrame

  • Class JFrame is known as a top-level window
  • Provides a basic window structure that connects Java to the operating system
  • Has a title, border and buttons for closing and iconifying the window
  • Inherits the paint method from class Container
  • Provides an object we can use for drawing upon

7.1.4: Color Control

  • Class Color defines the methods and constants for manipulating colors
  • Colors are created from red, green and blue (RGB) values
  • Color(float r, float g, float b) // 0.0 - 1.0
    Color(int r, int g, int b) // 0 - 255
    
  • For example:
  • Color brown = new Color(204, 102, 0);
    
  • To set a color, use the setColor method
  • For example:
  • public void paint(Graphics g) {
        Color brown = new Color(204, 102, 0);
        g.setColor(brown);
    }
    
  • Example 12.5 from textbook demonstrates several Color methods
  • import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class ShowColors extends JFrame {
    
       public ShowColors()
       {
          super( "Using colors" );
    
          setSize( 400, 130 );
          show();
       }
    
       // draw rectangles and Strings in various colors
       public void paint( Graphics g )
       {
          // call superclass's paint method
          super.paint( g );
    
          // set new drawing color using integers
          g.setColor( new Color( 255, 0, 0 ) );
          g.fillRect( 25, 25, 100, 20 );
          g.drawString( "Current RGB: "
                + g.getColor(), 130, 40 );
    
          // set new drawing color using floats
          g.setColor( new Color( 0.0f, 1.0f, 0.0f ) );
          g.fillRect( 25, 50, 100, 20 );
          g.drawString( "Current RGB: "
                + g.getColor(), 130, 65 );
    
          // set new drawing color using static Colors
          g.setColor( Color.blue );
          g.fillRect( 25, 75, 100, 20 );
          g.drawString( "Current RGB: "
                + g.getColor(), 130, 90 );
    
          // display individual RGB values
          Color color = Color.magenta;
          g.setColor( color );
          g.fillRect( 25, 100, 100, 20 );
          g.drawString( "RGB values: "
                + color.getRed() + ", "
                + color.getGreen() + ", "
                + color.getBlue(), 130, 115 );
       }
    
       // execute application
       public static void main( String args[] )
       {
          ShowColors application = new ShowColors();
    
          application.setDefaultCloseOperation(
             JFrame.EXIT_ON_CLOSE );
       }
    
    }  // end class ShowColors
    
  • A few comments:
  • public void paint(Graphics g)
    
  • Paints the window when application starts
  • g.setColor(new Color(255, 0, 0));
    
  • Method setColor sets color’s RGB value
  • g.fillRect(25, 25, 100, 20);
    
  • Method fillRect creates filled rectangle at specified coordinates using current RGB value
  • g.drawString("Current RGB: " + g.getColor(),130,40);
    
  • Method drawString draws colored text at specified coordinates
  • g.setColor(Color.BLUE);
    
  • Uses a constant from class Color to specify current color

7.1.5: Font Control

  • A font is a style of text
  • Class Font contains methods and constants for font control
  • Font constructor takes three arguments
    • Font name: Monospaced, SansSerif, Serif, etc.
    • Font style: Font.PLAIN, Font.ITALIC and Font.BOLD
    • Font size: measured in points (1/72 of inch)
    • Note that point sizes are only approximate
  • For example:
  • Font f = new Font("Serif",
                      Font.BOLD | Font.ITALIC,
                      POINT_SIZE);
    g.setFont(f);
    
  • Method setFont in a Graphics object can be used to change the current font
  • Java guarantees that at least three fonts will be available:
    • Monospaced
    • SanSerif
    • Serif
  • Programs can use the drawString method to display text on the screen.
  • First parameter tells which characters to display.
  • Last two parameters are coordinates specifying location of the text
  • For example:
  • g.drawString("My text", X_START, Y_START);
    

Exercise 7.1

Take one minute to prepare an answers to the following question:

  1. Where is the origin point of the graphics screen?
  2. How does one invoke the paint method?
  3. What data types does the constructor of the Color class take?
  4. What do the coordinates (x,y) given to the text rendering methods of Graphics describe?

7.2: Drawing

Objectives

At the end of the lesson the student will be able to:

  • Draw lines, rectangle and ovals
  • Draw arcs and polygons

7.2.1: Drawing Lines and Shapes

  • Class Graphics provides methods for drawing lines, rectangles and ovals
  • All drawing methods require parameters width and height
  • Most methods for painting shapes have two versions:
  • Draw version which only draws the outline of the shape (e.g. drawOval)
  • Fill version which fills in the shape (e.g. fillOval)
  • Example 12.14 from textbook demonstrates drawing lines, rectangles and ovals
  • import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class LinesRectsOvals extends JFrame {
    
       // set window's title bar String and dimensions
       public LinesRectsOvals()
       {
          super("Drawing lines, rectangles and ovals");
    
          setSize( 400, 165 );
          show();
       }
    
       // display various lines, rectangles and ovals
       public void paint( Graphics g )
       {
          // call superclass's paint method
          super.paint( g );
    
          g.setColor( Color.red );
          g.drawLine( 5, 30, 350, 30 );
    
          g.setColor( Color.blue );
          g.drawRect( 5, 40, 90, 55 );
          g.fillRect( 100, 40, 90, 55 );
    
          g.setColor( Color.cyan );
          g.fillRoundRect( 195, 40, 90, 55, 50, 50 );
          g.drawRoundRect( 290, 40, 90, 55, 20, 20 );
    
          g.setColor( Color.yellow );
          g.draw3DRect( 5, 100, 90, 55, true );
          g.fill3DRect( 100, 100, 90, 55, false );
    
          g.setColor( Color.magenta );
          g.drawOval( 195, 100, 90, 55 );
          g.fillOval( 290, 100, 90, 55 );
       }
    
       // execute application
       public static void main( String args[] )
       {
          LinesRectsOvals application =
                new LinesRectsOvals();
    
          application.setDefaultCloseOperation(
             JFrame.EXIT_ON_CLOSE );
       }
    
    }  // end class LinesRectsOvals
    
  • A few comments:
  • g.fillRoundRect( 195, 40, 90, 55, 50, 50 );
    
  • Draws a filled rounded rectangle
  • g.drawRoundRect( 290, 40, 90, 55, 20, 20 );
    
  • Draws a non-filled rounded rectangle
  • g.draw3DRect( 5, 100, 90, 55, true );
    
  • Draws a "3D" (raised) rectangle
  • g.fill3DRect( 100, 100, 90, 55, false );
    
  • Draws a filled 3D rectangle
  • g.drawOval( 195, 100, 90, 55 );
    
  • Draws an oval
  • g.fillOval( 290, 100, 90, 55 );
    
  • Draws a filled oval

7.2.2: Drawing Arcs

  • Arcs are just a portion of an oval
  • Specify the beginning angle and the degrees of the sweep
  • g.drawArc(x, y, width, height, startAngle, arcAngle);
    
  • Sweeps the number of degrees in arc angle
  • Sweep starts at starting angle
  • Counterclockwise sweep is measure in positive degrees
  • Clockwise sweep is measure in negative degrees

7.2.3: Drawing Polygons

  • Method drawPolygon draws shapes with any number of sides
  • public void drawPolygon(int[] x, int[] y, int nPoints)
    
  • Each x and y in series drawn from the array parameters
  • Third parameter tells how many points to draw
  • Always draws a closed polygon
  • If first and last points are not equal, draws a line from last to first
  • fillPolygon is similar but fills with color instead of drawing outline.
  • public void fillPolygon(int[] x, int[] y, int nPoints)
    
  • drawPolyline is similar but can draw an open figure.
  • public void drawPolyline(int[] x, int[] y, int nPoints)
    
  • Example 12.21 from textbook demonstrates drawing polygons
  • import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class DrawPolygons extends JFrame {
    
       // set window's title bar and dimensions
       public DrawPolygons()
       {
          super( "Drawing Polygons" );
    
          setSize( 275, 230 );
          show();
       }
    
       // draw polygons and polylines
       public void paint( Graphics g )
       {
          // call superclass's paint method
          super.paint( g );
    
          int xValues[] = { 20, 40, 50, 30, 20, 15 };
          int yValues[] = { 50, 50, 60, 80, 80, 60 };
          Polygon polygon1 =
                new Polygon( xValues, yValues, 6 );
    
          g.drawPolygon( polygon1 );
    
          int xValues2[] =
                { 70, 90, 100, 80, 70, 65, 60 };
          int yValues2[] =
                { 100, 100, 110, 110, 130, 110, 90 };
    
          g.drawPolyline( xValues2, yValues2, 7 );
    
          int xValues3[] = { 120, 140, 150, 190 };
          int yValues3[] = { 40, 70, 80, 60 };
    
          g.fillPolygon( xValues3, yValues3, 4 );
    
          Polygon polygon2 = new Polygon();
          polygon2.addPoint( 165, 135 );
          polygon2.addPoint( 175, 150 );
          polygon2.addPoint( 270, 200 );
          polygon2.addPoint( 200, 220 );
          polygon2.addPoint( 130, 180 );
    
          g.fillPolygon( polygon2 );
       }
    
       // execute application
       public static void main( String args[] )
       {
          DrawPolygons application =
                new DrawPolygons();
    
          application.setDefaultCloseOperation(
             JFrame.EXIT_ON_CLOSE );
       }
    
    }  // end class DrawPloygons
    
  • A few comments:
  • int xValues[] = { 20, 40, 50, 30, 20, 15 };
    int yValues[] = { 50, 50, 60, 80, 80, 60 };
    
  • int arrays specifying Polygon points
  • Polygon polygon1 = new Polygon(xValues yValues,6);
    g.drawPolygon( polygon1 );
    
  • Draw polygon1 to screen
  • int xValues2[] = {70, 90, 100, 80, 70, 65, 60};
    int yValues2[] = {100,100,110,110,130,110,90};
    
  • int arrays specifying Polygon polygon2 points
  • g.drawPolyline( xValues2, yValues2, 7 );
    
  • Draw polygon2 to screen
  • int xValues3[] = { 120, 140, 150, 190 };
    int yValues3[] = { 40, 70, 80, 60 };
    g.fillPolygon( xValues3, yValues3, 4 );
    
  • Specify Polygon points and draw (filled) polygon3 to screen
  • Polygon polygon2 = new Polygon();
    polygon2.addPoint( 165, 135 );
    polygon2.addPoint( 175, 150 );
    polygon2.addPoint( 270, 200 );
    polygon2.addPoint( 200, 220 );
    polygon2.addPoint( 130, 180 );
    
  • Method addPoint adds pairs of (x,y) coordinates to Polygon
  • More information: Class Graphics

7.2.4: Java 2D

  • Java 2D API provides advanced 2D graphics capabilities
    • Draw lines of any thickness
    • Fill shapes with gradients and textures
    • Move, rotate, scale, and shear text and graphics
    • Composite overlapping text and graphics
  • Drawing needs an instance of Graphics2D
  • Graphics2D is subclass of Graphics
  • To access Graphics2D in paint, need to downcast from Graphics
  • For example:
  • public void paint(Graphics g) {
        Graphics2D g2d = (Graphics2D)g;
        // do something with g2d
    }
    
  • Java 2D shapes from the Package java.awt.geom
    • Ellipse2D.Double
    • Rectangle2D.Double
    • RoundRectangle2D.Double
    • Arc3D.Double
    • Lines2D.Double
  • Note the syntax of each class
  • Double is a static inner class of the shape
    • Will discuss inner classes later in course
  • Example 12.22 from textbook demonstrates drawing with Java2D shapes
// Fig. 11.22: Shapes.java
// Demonstrating some Java2D shapes

// Java core packages
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;

// Java extension packages
import javax.swing.*;

public class Shapes2D extends JFrame {

   // set window's title bar String and dimensions
   public Shapes2D()
   {
      super( "Drawing 2D shapes" );

      setSize( 425, 160 );
      show();
   }

   // draw shapes with Java2D API
   public void paint( Graphics g )
   {
      // call superclass's paint method
      super.paint( g );

      // create 2D by casting g to Graphics2D
      Graphics2D g2d = ( Graphics2D ) g;

      // draw 2D ellipse filled with a blue-yellow
      // gradient
      g2d.setPaint( new GradientPaint( 5, 30,
            Color.blue, 35, 100, Color.yellow, true));
      g2d.fill(new Ellipse2D.Double(5, 30, 65, 100));

      // draw 2D rectangle in red
      g2d.setPaint( Color.red );
      g2d.setStroke( new BasicStroke( 10.0f ) );
      g2d.draw(new Rectangle2D.Double(80, 30, 65, 100));

      // draw 2D rounded rectangle with a buffered
      // background
      BufferedImage buffImage = new BufferedImage(
         10, 10, BufferedImage.TYPE_INT_RGB );

      Graphics2D gg = buffImage.createGraphics();
      gg.setColor(Color.yellow); // yellow
      gg.fillRect(0, 0, 10, 10); // filled rectangle
      gg.setColor(Color.black);  // black
      gg.drawRect(1, 1, 6, 6);   // rectangle
      gg.setColor(Color.blue);   // blue
      gg.fillRect(1, 1, 3, 3);   // filled rectangle
      gg.setColor(Color.red);    // red
      gg.fillRect(4, 4, 3, 3);   // filled rectangle

      // paint buffImage onto the JFrame
      g2d.setPaint( new TexturePaint(
         buffImage, new Rectangle( 10, 10 ) ) );
      g2d.fill( new RoundRectangle2D.Double(
         155, 30, 75, 100, 50, 50 ) );

      // draw 2D pie-shaped arc in white
      g2d.setPaint( Color.white );
      g2d.setStroke( new BasicStroke( 6.0f ) );
      g2d.draw( new Arc2D.Double(
         240, 30, 75, 100, 0, 270, Arc2D.PIE ) );

      // draw 2D lines in green and yellow
      g2d.setPaint( Color.green );
      g2d.draw( new Line2D.Double( 395, 30, 320, 150 ) );

      float dashes[] = { 10 };

      g2d.setPaint( Color.yellow );
      g2d.setStroke( new BasicStroke( 4,
            BasicStroke.CAP_ROUND,
            BasicStroke.JOIN_ROUND, 10, dashes, 0 ) );
      g2d.draw( new Line2D.Double( 320, 30, 395, 150 ) );
   }

   // execute application
   public static void main( String args[] )
   {
      Shapes2D application = new Shapes2D();

      application.setDefaultCloseOperation(
         JFrame.EXIT_ON_CLOSE );
   }

}  // end class Shapes
  • A few comments:
  • g2d.setPaint( new GradientPaint( 5, 30, Color.blue,
        35, 100, Color.yellow, true ) );
    
  • Use GradientPaint to fill shape with gradient
  • g2d.fill( new Ellipse2D.Double( 5, 30, 65, 100 ) );
    
  • Fill ellipse with gradient
  • g2d.setStroke( new BasicStroke( 10.0f ) );
    g2d.draw(new Rectangle2D.Double( 80, 30, 65, 100));
    
  • Use BasicStroke to draw 2D red-border rectangle
  • BufferedImage buffImage = new BufferedImage(
        10, 10, BufferedImage.TYPE_INT_RGB );
    
  • BufferedImage produces image to be manipulated
  • Graphics2D gg = buffImage.createGraphics();
    gg.setColor(Color.yellow); // yellow
    gg.fillRect(0, 0, 10, 10); // filled rectangle
    gg.setColor(Color.black);  // black
    gg.drawRect(1, 1, 6, 6);   // rectangle
    gg.setColor(Color.blue);   // blue
    gg.fillRect(1, 1, 3, 3);   // filled rectangle
    gg.setColor(Color.red);    // red
    gg.fillRect(4, 4, 3, 3);   // filled rectangle
    
  • Draw texture into BufferedImage
  • g2d.fill( new RoundRectangle2D.Double(
        155, 30, 75, 100, 50, 50 ) );
    
  • Use BufferedImage as texture for painting rounded rectangle
  • g2d.draw( new Arc2D.Double(
        240, 30, 75, 100, 0, 270, Arc2D.PIE ) );
    
  • Use Arc2D.PIE to draw white-border 2D pie-shaped arc

More Information

Exercise 7.2

Take one minute to prepare an answers to the following question:

  1. What is the size of the area affected by the following code?
  2. public void paint(Graphics g) {
        g.fillRect(10, 10, 30, 30);
    }
    
    1. 19 x 19 pixels
    2. 20 x 20 pixels
    3. 21 x 21 pixels
    4. 29 x 29 pixels
    5. 30 x 30 pixels
    6. 31 x 31 pixels

7.3: Midterm Review

Objectives

At the end of the lesson the student will be able to:

  • Describe how to prepare for the midterm exam
  • Describe how to take the midterm exam

7.3.1: About the Midterm Exam

Important Midterm Exam Information

Date and Time: 10/29/03 between 6:00 PM and 9:10 PM
Duration: 180 minutes (3 hours)
Location: WebCT

  • I will be using WebCT to administer the exam
  • Do not come to the classroom for the test
    • Instead, find a computer with a fast Internet connection (such as the CTC)
  • The exam is designed to take about 1 to 1.5 hours to complete
  • However, you will have the full scheduled time to complete the exam
  • You can use your computer, notes and textbook
  • You may NOT discuss the exam with anyone (except me) during the exam period
  • You can view your partial scores after the exam period is over

7.3.2: Exam Taking Tips

  • Save after every answer -- you can always choose another answer
  • If you get stuck on a question, make your best guess and return later
  • If you are equally uncertain between two choices, go with first impression
  • You do not need to comment code for tests and exams
    • Unless specifically instructed to in the exam question
  • Use the full time available
  • Try Site Search to help you recall words or phrases
  • More quiz tips: Basic Rules For Taking a Multiple-Choice Test

7.3.3: Recommended Preparation

  1. Review your homework assignments and solutions
  2. Work through the Practice Midterm Exam questions in WebCT
    • Working the problems in groups is encouraged
    • Get explanations for anything you do not understand
  3. Get plenty of rest before the exam

Wrap Up

Home | WebCT | Announcements | Schedule | Expectations | Syllabus
Help | FAQ's | HowTo's | Links

Last Updated: October 22 2003 @17:04:46