SlideShare a Scribd company logo
1 of 32
Chapter 13 Graphics




Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                     rights reserved.
                                                                                               1
Motivations
If you want to draw shapes such as a bar chart, a
clock, or a stop sign, how do you do it?




         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                              rights reserved.
                                                                                                        2
Objectives
   To describe Java coordinate systems in a GUI component (§13.2).
   To draw things using the methods in the Graphics class (§13.3).
   To override the paintComponent method to draw things on a GUI
    component (§13.3).
   To use a panel as a canvas to draw things (§13.3).
   To draw strings, lines, rectangles, ovals, arcs, and polygons
    (§§13.4, 13.6-13.7).
   To obtain font properties using FontMetrics and know how to
    center a message (§13.8).
   To display an image in a GUI component (§13.11).
   To develop reusable GUI components FigurePanel, MessagePanel,
    StillClock, and ImageViewer (§§13.5, 13.9, 13.10, 13.12).




              Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                   rights reserved.
                                                                                                             3
Java Coordinate System

              x
                                                                                                      Y Axis
    (0, 0)                          X Axis


y
             (x, y)
                                                                                                   (0, 0)      X Axis
                       Java Coordinate                                 Conventional
                       System                                          Coordinate
                                                                       System
    Y Axis




             Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                  rights reserved.
                                                                                                                   4
Each GUI Component Has its
    Own Coordinate System

(x3, y3)                                                                                                  c3’s coordinate
           (0, 0)                               Component c3
                                                                                                          system

             (x2, y2)
                         (0, 0)                         Component c2                                      c2’s coordinate
                                                                                                          system
                          (x1, y1)
                                       (0, 0)      Component c1
                                                                                                          c1’s coordinate
                                                                                                          system




           Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                rights reserved.
                                                                                                                5
The Graphics Class
                                                        java.awt.Graphics

You can draw strings,                   +setColor(color: Color): void
                                        +setFont(font: Font): void
                                                                                            Sets a new color for subsequent drawings.
                                                                                            Sets a new font for subsequent drwings.
lines, rectangles, ovals,               +drawString(s: String, x: int, y: int): void         Draws a string starting at point (x, y).
                                        +drawLine(x1: int, y1: int, x2: int, y2: int): void Draws a line from (x1, y1) to (x2, y2).
arcs, polygons, and                     +drawRect(x: int, y: int, w: int, h: int): void      Draws a rectangle with specified upper-left corner point at (x,
                                                                                                y) and width w and height h.
polylines, using the                    +fillRect(x: int, y: int, w: int, h: int): void      Draws a filled rectangle with specified upper-left corner point
                                                                                                at (x, y) and width w and height h.
methods in the Graphics                 +drawRoundRect(x: int, y: int, w: int, h: int, aw: Draws a round-cornered rectangle with specified arc width aw
                                            int, ah: int): void                                 and arc height ah.

class.                                  +fillRoundRect(x: int, y: int, w: int, h: int, aw:
                                            int, ah: int): void
                                                                                             Draws a filled round-cornered rectangle with specified arc
                                                                                                width aw and arc height ah.
                                        +draw3DRect(x: int, y: int, w: int, h: int, raised: Draws a 3-D rectangle raised above the surface or sunk into the
                                            boolean): void                                      surface.
                                        +fill3DRect(x: int, y: int, w: int, h: int, raised:  Draws a filled 3-D rectangle raised above the surface or sunk
                                            boolean): void                                      into the surface.
                                        +drawOval(x: int, y: int, w: int, h: int): void      Draws an oval bounded by the rectangle specified by the
                                                                                                parameters x, y, w, and h.
                                        +fillOval(x: int, y: int, w: int, h: int): void      Draws a filled oval bounded by the rectangle specified by the
                                                                                                parameters x, y, w, and h.
                                        +drawArc(x: int, y: int, w: int, h: int, startAngle: Draws an arc conceived as part of an oval bounded by the
                                            int, arcAngle: int): void                           rectangle specified by the parameters x, y, w, and h.
                                        +fillArc(x: int, y: int, w: int, h: int, startAngle: Draws a filled arc conceived as part of an oval bounded by the
                                            int, arcAngle: int): void                           rectangle specified by the parameters x, y, w, and h.
                                        +drawPolygon(xPoints: int[], yPoints: int[],         Draws a closed polygon defined by arrays of x and y
                                            nPoints: int): void                                 coordinates. Each pair of (x[i], y[i]) coordinates is a point.
                                        +fillPolygon(xPoints: int[], yPoints: int[],         Draws a filled polygon defined by arrays of x and y
                                            nPoints: int): void                                 coordinates. Each pair of (x[i], y[i]) coordinates is a point.
                                        +drawPolygon(g: Polygon): void                       Draws a closed polygon defined by a Polygon object.
                                        +fillPolygon(g: Polygon): void                      Draws a filled polygon defined by a Polygon object.
                                        +drawPolyline(xPoints: int[], yPoints: int[],       Draws a polyline defined by arrays of x and y coordinates.
                                           nPoints: int): void                                 Each pair of (x[i], y[i]) coordinates is a point.

             Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                  rights reserved.
                                                                                                                                                    6
paintComponent Example
In order to draw things on a component, you need
to define a class that extends JPanel and overrides
its paintComponent method to specify what to
draw. The first program in this chapter can be
rewritten using paintComponent.




                             TestPaintComponent                                                         Run
         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                              rights reserved.
                                                                                                              7
Drawing Geometric Figures
   Drawing Strings
   Drawing Lines
   Drawing Rectangles
   Drawing Ovals
   Drawing Arcs
   Drawing Polygons



        Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                             rights reserved.
                                                                                                       8
Drawing Strings

    (0, 0)                               (getWidth(), 0)                         (0, 0)                                  (getWidth(), 0)

                                                                                              (x1, y1)

(x, y)               s is display here
                                                                                                                  (x2, y2)

  (0, getHeight())                 (getWidth(), getHeight())                   (0, getHeight())                     (getWidth(), getHeight())




    drawString(String s, int x, int y);                                          drawLine(int x1, int y1, int x2, int y2);




                          Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                               rights reserved.
                                                                                                                                           9
Drawing Rectangles
 drawRect(int x, int y, int w, int h);
                                         fillRect(int x, int y, int w, int h);

(x, y)                                                             (x, y)



                                     h                                                                    h



           w                                                                                  w




           Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                rights reserved.
                                                                                                              10
Drawing Rounded Rectangles
drawRoundRect(int x, int y, int w, int h, int aw, int ah);
fillRoundRect(int x, int y, int w, int h, int aw, int ah);

              (x, y)
                                        ah/2

                            aw/2

                                                                                               h




                                                          w


           Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                rights reserved.
                                                                                                          11
Drawing Ovals
drawOval(int x, int y, int w, int h);
fillOval(int x, int y, int w, int h);
(x, y)




                                                      h




               w




           Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                rights reserved.
                                                                                                          12
Case Study: The FigurePanel Class
This example develops a useful class for displaying various
figures. The class enables the user to set the figure type and
specify whether the figure is filled, and displays the figure on a
panel.                  javax.swing.JPanel
                              -char token

                              +getToken      FigurePanel
                              +setToken
                              +paintComponet                                 LINE, RECTANGLE,
                               +LINE = 1
                              +mouseClicked                                  ROUND_RECTANGLE, and OVAL are
                               +RECTANGLE = 2                                constants.
                               +ROUND_RECTANGLE = 3
                               +OVAL = 4
                               -type: int                                 Specifies the figure type (default: 1).
                               -filled: boolean                           Specifies whether the figure is filled (default: false).

                               +FigurePanel()                             Creates a default figure panel.
                               +FigurePanel(type: int)                    Creates a figure panel with the specified type.
                               +FigurePanel(type: int, filled: boolean)   Creates a figure panel with the specified type and filled property.
                               +getType(): int                            Returns the figure type.
                               +setType(type: int): void                  Sets a new figure type.
 FigurePanel                   +isFilled(): boolean                       Checks whether the figure is filled with a color.
                               +setFilled(filled: boolean): void          Sets a new filled property.

            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                                                 13
Test FigurePanel
This example develops a useful class for displaying various
figures. The class enables the user to set the figure type and
specify whether the figure is filled, and displays the figure on a
panel.




                                      TestFigurePanel                                                      Run
            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                                 14
Drawing Arcs
drawArc(int x, int y, int w, int h, int angle1, int angle2);
fillArc(int x, int y, int w, int h, int angle1, int angle2);



                                                                                                   Angles are in
                                                                                                   degree




         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                              rights reserved.
                                                                                                            15
Drawing Arcs Example




                                                 DrawArcs                                      Run
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                     rights reserved.
                                                                                                     16
Drawing Polygons and Polylines
int[] x = {40, 70, 60, 45, 20};
int[] y = {20, 40, 80, 45, 60};                                         g.drawPolyline(x, y, x.length);
g.drawPolygon(x, y, x.length);


  (x[0], y[0])                                                                (x[0], y[0])
                                            (x[1], y[1])                                                                  (x[1], y[1])
                 (x[3], y[3])                                                                 (x[3], y[3])



(x[4], y[4])                                                               (x[4], y[4])
                                  (x[2], y[2])                                                                   (x[2], y[2])




                       Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                            rights reserved.
                                                                                                                                    17
Drawing Polygons Using the
      Polygon Class
Polygon polygon = new Polygon();
polygon.addPoint(40, 59);
polygon.addPoint(40, 100);
polygon.addPoint(10, 100);
g.drawPolygon(polygon);




  Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                       rights reserved.
                                                                                                 18
Drawing Polygons Example




                                        DrawPolygon                                        Run

 Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                      rights reserved.
                                                                                                 19
Centering Display Using the FontMetrics Class
You can display a string at any location in a panel. Can you display
it centered? To do so, you need to use the FontMetrics class to
measure the exact width and height of the string for a particular
font. A FontMetrics can measure the following attributes:

   public int getAscent()                                   public int getHeight()
   public int getDescent()                                  public int stringWidth(String str)
   public int getLeading()

                                                                                                              getLeading()

getHeight()
                                                                                                              getAscent()


                                                                                                              getDescent()
               Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                    rights reserved.
                                                                                                                  20
The FontMetrics Class

FontMetrics is an abstract class. To get a FontMetrics
object for a specific font, use the following
getFontMetrics methods defined in the Graphics class:

   · public FontMetrics getFontMetrics(Font f)
Returns the font metrics of the specified font.

   · public FontMetrics getFontMetrics()
Returns the font metrics of the current font.

          Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                               rights reserved.
                                                                                                         21
panel




                                                                 stringWidth
getHeight()
              stringAscent
                                     Welcome to Java

                                                           getWidth()




              TestCenterMessage                                                   Run

               Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                    rights reserved.
                                                                                                              22
Case Study: MessagePanel
       javax.swing.JPanel
                                           The get and set methods for these data                   This case study
                                           fields are provided in the class, but
-char token
                                           omitted in the UML diagram                               develops a useful class
+getToken MessagePanel
+setToken
                                                                                                    that displays a message
+paintComponet
+mouseClicked int
-xCoordinate:                     The x-Coordinate for the message (default 20).                    in a panel. The class
-yCoordinate: int
-centered: boolean
                                  The y-Coordinate for the message (default 20).
                                  Specifies whether the message is displayed centered.
                                                                                                    enables the user to set
-message: String                  The message to be displayed.                                      the location of the
-interval: int                    The interval to move the message in the panel.
                                                                                                    message, center the
+MessagePanel()
+MessagePanel(message: String)
                                  Constructs a default message panel.
                                  Constructs a message panel with a specified string.
                                                                                                    message, and move the
+moveLeft(): void                 Moves the message to the left.                                    message with the
+moveRight(): void                Moves the message to the right.
+moveUp(): void                   Moves the message up.                                             specified interval.
+moveDown(): void                 Moves the message down.




              MessagePanel                           TestMessagePanel                                                   Run
                         Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                              rights reserved.
                                                                                                                              23
Case Study: StillClock

       javax.swing.JPanel                 The get and set methods for these data
                                          fields are provided in the class, but
-char token                               omitted in the UML diagram

+getToken StillClock
+setToken
+paintComponet
-hour: int
+mouseClicked                      The hour in the clock.
-minute: int                       The minute in the clock.
-second: int                       The second in the clock.

+StillClock()                      Constructs a default clock for the current time.
+StillClock(hour: int, minute: int, Constructs a clock with a specified time.
  second: int)
+setCurrentTime(): void             Sets time to current time.




              StillClock                                 DisplayClock                                                  Run
                        Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                             rights reserved.
                                                                                                                             24
Drawing Clock
xEnd = xCenter + handLength                         sin( ) Since there are sixty seconds
                                                           in one minute, the angle for
yEnd = yCenter - handLength                        cos( ) the second hand is

                                                                      second               (2 /60)




             Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                  rights reserved.
                                                                                                            25
Drawing Clock, cont.
           xEnd = xCenter + handLength                                       sin( )
           yEnd = yCenter - handLength                                      cos( )

The position of the minute hand is
determined by the minute and
second. The exact minute value
combined with seconds is minute +
second/60. For example, if the time
is 3 minutes and 30 seconds. The
total minutes are 3.5. Since there are
sixty minutes in one hour, the angle
for the minute hand is
(minute + second/60) (2 /60)
               Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                    rights reserved.
                                                                                                              26
Drawing Clock, cont.
xEnd = xCenter + handLength                            sin( )
yEnd = yCenter - handLength                           cos( )

Since one circle is divided into
twelve hours, the angle for the
hour hand is
(hour + minute/60 + second/(60
  60))) (2 /12)




            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                           27
Displaying Image Icons
You learned how to create image icons and display image icons in
labels and buttons. For example, the following statements create an
image icon and display it in a label:

ImageIcon icon = new ImageIcon("image/us.gif");
JLabel jlblImage = new JLabel(imageIcon);

An image icon displays a fixed-size image. To display an image in a
flexible size, you need to use the java.awt.Image class. An image can
be created from an image icon using the getImage() method as
follows:

Image image = imageIcon.getImage();

            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                           28
Displaying Images
Using a label as an area for displaying images is simple and
convenient, but you don't have much control over how the image is
displayed. A more flexible way to display images is to use the
drawImage method of the Graphics class on a panel. Four versions
of the drawImage method are shown here.
         java.awt.Graphics
+drawImage(image: Image, x: int, y: int,        Draws the image in a specified location. The image's top-left corner is at
  bgcolor: Color, observer:                       (x, y) in the graphics context's coordinate space. Transparent pixels in
  ImageObserver): void                            the image are drawn in the specified color bgcolor. The observer is the
                                                  object on which the image is displayed. The image is cut off if it is
                                                  larger than the area it is being drawn on.
+drawImage(image: Image, x: int, y: int,        Same as the preceding method except that it does not specify a background
  observer: ImageObserver): void                  color.
+drawImage(image: Image, x: int, y: int,        Draws a scaled version of the image that can fill all of the available space
  width: int, height: int, observer:              in the specified rectangle.
  ImageObserver): void
+drawImage(image: Image, x: int, y: int, Same as the preceding method except that it provides a solid background
  width: int, height: int, bgcolor: Color, color behind the image being drawn.
  observer: ImageObserver): void
                     Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                          rights reserved.
                                                                                                                     29
Displaying Images Example
This example gives the code that displays an image from
image/us.gif. The file image/us.gif is under the class directory. The
Image from the file is created in the program. The drawImage
method displays the image to fill in the whole panel, as shown in the
figure.




                                              DisplayImage                                                  Run
             Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                  rights reserved.
                                                                                                                  30
Case Study: ImageViewer Class
Displaying an image is a common task in Java programming. This
case study develops a reusable component named ImageViewer that
displays an image in a panel. The ImageViewer class contains the
properties image, imageFilename, stretched, xCoordinate, and
yCoordinate.
     javax.swing.JPanel                                The get and set methods for these data
                                                       fields are provided in the class, but
                                                       omitted in the UML diagram for brevity.
         ImageViewer
  -image: Image                              Image in the image viewer.
  -stretched: boolean                        True if the image is stretched in the viewer.
  -xCoordinate: int                          x-coordinate of the upper-left corner of the image in the viewer.
  -yCoordinate: int                          y-coordinate of the upper-left corner of the image in the viewer.

  +ImageViewer()                             Constructs an image viewer with no image.
  +ImageViewer(imageFile: String)            Constructs an image viewer with the specified image file.

                  Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                       rights reserved.
                                                                                                                 31
ImageView Example
This example gives an example that creates six images using the
ImageViewer class.




                                                    SixFlags                                               Run
            Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
                                                 rights reserved.
                                                                                                                 32

More Related Content

What's hot

Submodularity slides
Submodularity slidesSubmodularity slides
Submodularity slides
dragonthu
 
05 history of cv a machine learning (theory) perspective on computer vision
05  history of cv a machine learning (theory) perspective on computer vision05  history of cv a machine learning (theory) perspective on computer vision
05 history of cv a machine learning (theory) perspective on computer vision
zukun
 
11.performance evaluation of geometric active contour (gac) and enhanced geom...
11.performance evaluation of geometric active contour (gac) and enhanced geom...11.performance evaluation of geometric active contour (gac) and enhanced geom...
11.performance evaluation of geometric active contour (gac) and enhanced geom...
Alexander Decker
 
Lecture8 multi class_svm
Lecture8 multi class_svmLecture8 multi class_svm
Lecture8 multi class_svm
Stéphane Canu
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]
Palak Sanghani
 

What's hot (18)

Computer graphics
Computer graphics Computer graphics
Computer graphics
 
Ben Gal
Ben Gal Ben Gal
Ben Gal
 
Functional Programming in C++
Functional Programming in C++Functional Programming in C++
Functional Programming in C++
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
 
Mesh Processing Course : Geodesic Sampling
Mesh Processing Course : Geodesic SamplingMesh Processing Course : Geodesic Sampling
Mesh Processing Course : Geodesic Sampling
 
Discrete Models in Computer Vision
Discrete Models in Computer VisionDiscrete Models in Computer Vision
Discrete Models in Computer Vision
 
Submodularity slides
Submodularity slidesSubmodularity slides
Submodularity slides
 
Lecture9
Lecture9Lecture9
Lecture9
 
05 history of cv a machine learning (theory) perspective on computer vision
05  history of cv a machine learning (theory) perspective on computer vision05  history of cv a machine learning (theory) perspective on computer vision
05 history of cv a machine learning (theory) perspective on computer vision
 
MATLAB & Image Processing
MATLAB & Image ProcessingMATLAB & Image Processing
MATLAB & Image Processing
 
Performance evaluation of geometric active contour (gac) and enhanced geometr...
Performance evaluation of geometric active contour (gac) and enhanced geometr...Performance evaluation of geometric active contour (gac) and enhanced geometr...
Performance evaluation of geometric active contour (gac) and enhanced geometr...
 
11.performance evaluation of geometric active contour (gac) and enhanced geom...
11.performance evaluation of geometric active contour (gac) and enhanced geom...11.performance evaluation of geometric active contour (gac) and enhanced geom...
11.performance evaluation of geometric active contour (gac) and enhanced geom...
 
Fundamentals of Image Processing & Computer Vision with MATLAB
Fundamentals of Image Processing & Computer Vision with MATLABFundamentals of Image Processing & Computer Vision with MATLAB
Fundamentals of Image Processing & Computer Vision with MATLAB
 
Lecture8 multi class_svm
Lecture8 multi class_svmLecture8 multi class_svm
Lecture8 multi class_svm
 
Lesson 2: A Catalog of Essential Functions
Lesson 2: A Catalog of Essential FunctionsLesson 2: A Catalog of Essential Functions
Lesson 2: A Catalog of Essential Functions
 
Curve fitting
Curve fittingCurve fitting
Curve fitting
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]
 
Computer graphics practical(jainam)
Computer graphics practical(jainam)Computer graphics practical(jainam)
Computer graphics practical(jainam)
 

Viewers also liked

Viewers also liked (12)

01slide
01slide01slide
01slide
 
java graphics
java graphicsjava graphics
java graphics
 
Applet and graphics programming
Applet and graphics programmingApplet and graphics programming
Applet and graphics programming
 
Ch2 Liang
Ch2 LiangCh2 Liang
Ch2 Liang
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
 
Graphics programming in Java
Graphics programming in JavaGraphics programming in Java
Graphics programming in Java
 
27 applet programming
27  applet programming27  applet programming
27 applet programming
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Core java slides
Core java slidesCore java slides
Core java slides
 
Java Graphics Programming
Java Graphics ProgrammingJava Graphics Programming
Java Graphics Programming
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 

Similar to JavaYDL13

Mathematical sciences-paper-ii
Mathematical sciences-paper-iiMathematical sciences-paper-ii
Mathematical sciences-paper-ii
knowledgesociety
 
6 3 d coordinate systems
6 3 d coordinate  systems6 3 d coordinate  systems
6 3 d coordinate systems
math267
 
TAO Fayan_X-Ray and MIP volume rendering
TAO Fayan_X-Ray and MIP volume renderingTAO Fayan_X-Ray and MIP volume rendering
TAO Fayan_X-Ray and MIP volume rendering
Fayan TAO
 

Similar to JavaYDL13 (20)

13slide graphics
13slide graphics13slide graphics
13slide graphics
 
graphics programming in java
graphics programming in javagraphics programming in java
graphics programming in java
 
Applets
AppletsApplets
Applets
 
raster algorithm.pdf
raster algorithm.pdfraster algorithm.pdf
raster algorithm.pdf
 
Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1Computer Graphics in Java and Scala - Part 1
Computer Graphics in Java and Scala - Part 1
 
lect.no.3.pptx
lect.no.3.pptxlect.no.3.pptx
lect.no.3.pptx
 
Computer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1bComputer Graphics in Java and Scala - Part 1b
Computer Graphics in Java and Scala - Part 1b
 
Basic Graphics in Java
Basic Graphics in JavaBasic Graphics in Java
Basic Graphics in Java
 
Mathematical sciences-paper-ii
Mathematical sciences-paper-iiMathematical sciences-paper-ii
Mathematical sciences-paper-ii
 
1533 game mathematics
1533 game mathematics1533 game mathematics
1533 game mathematics
 
Programming with matlab session 6
Programming with matlab session 6Programming with matlab session 6
Programming with matlab session 6
 
Matlab plotting
Matlab plottingMatlab plotting
Matlab plotting
 
6 3 d coordinate systems
6 3 d coordinate  systems6 3 d coordinate  systems
6 3 d coordinate systems
 
Computer graphics notes 2 tutorials duniya
Computer graphics notes 2   tutorials duniyaComputer graphics notes 2   tutorials duniya
Computer graphics notes 2 tutorials duniya
 
TAO Fayan_X-Ray and MIP volume rendering
TAO Fayan_X-Ray and MIP volume renderingTAO Fayan_X-Ray and MIP volume rendering
TAO Fayan_X-Ray and MIP volume rendering
 
Mat lab
Mat labMat lab
Mat lab
 
JavaYDL15
JavaYDL15JavaYDL15
JavaYDL15
 
Windows and viewport
Windows and viewportWindows and viewport
Windows and viewport
 
SPSF02 - Graphical Data Representation
SPSF02 - Graphical Data RepresentationSPSF02 - Graphical Data Representation
SPSF02 - Graphical Data Representation
 
Revision1schema C programming
Revision1schema C programmingRevision1schema C programming
Revision1schema C programming
 

More from Terry Yoast

More from Terry Yoast (20)

9781305078444 ppt ch12
9781305078444 ppt ch129781305078444 ppt ch12
9781305078444 ppt ch12
 
9781305078444 ppt ch11
9781305078444 ppt ch119781305078444 ppt ch11
9781305078444 ppt ch11
 
9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10
 
9781305078444 ppt ch09
9781305078444 ppt ch099781305078444 ppt ch09
9781305078444 ppt ch09
 
9781305078444 ppt ch08
9781305078444 ppt ch089781305078444 ppt ch08
9781305078444 ppt ch08
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07
 
9781305078444 ppt ch06
9781305078444 ppt ch069781305078444 ppt ch06
9781305078444 ppt ch06
 
9781305078444 ppt ch05
9781305078444 ppt ch059781305078444 ppt ch05
9781305078444 ppt ch05
 
9781305078444 ppt ch04
9781305078444 ppt ch049781305078444 ppt ch04
9781305078444 ppt ch04
 
9781305078444 ppt ch03
9781305078444 ppt ch039781305078444 ppt ch03
9781305078444 ppt ch03
 
9781305078444 ppt ch02
9781305078444 ppt ch029781305078444 ppt ch02
9781305078444 ppt ch02
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13
 
9781337102087 ppt ch18
9781337102087 ppt ch189781337102087 ppt ch18
9781337102087 ppt ch18
 
9781337102087 ppt ch17
9781337102087 ppt ch179781337102087 ppt ch17
9781337102087 ppt ch17
 
9781337102087 ppt ch16
9781337102087 ppt ch169781337102087 ppt ch16
9781337102087 ppt ch16
 
9781337102087 ppt ch15
9781337102087 ppt ch159781337102087 ppt ch15
9781337102087 ppt ch15
 
9781337102087 ppt ch14
9781337102087 ppt ch149781337102087 ppt ch14
9781337102087 ppt ch14
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12
 
9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11
 

Recently uploaded

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 

Recently uploaded (20)

fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 

JavaYDL13

  • 1. Chapter 13 Graphics Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1
  • 2. Motivations If you want to draw shapes such as a bar chart, a clock, or a stop sign, how do you do it? Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 2
  • 3. Objectives  To describe Java coordinate systems in a GUI component (§13.2).  To draw things using the methods in the Graphics class (§13.3).  To override the paintComponent method to draw things on a GUI component (§13.3).  To use a panel as a canvas to draw things (§13.3).  To draw strings, lines, rectangles, ovals, arcs, and polygons (§§13.4, 13.6-13.7).  To obtain font properties using FontMetrics and know how to center a message (§13.8).  To display an image in a GUI component (§13.11).  To develop reusable GUI components FigurePanel, MessagePanel, StillClock, and ImageViewer (§§13.5, 13.9, 13.10, 13.12). Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 3
  • 4. Java Coordinate System x Y Axis (0, 0) X Axis y (x, y) (0, 0) X Axis Java Coordinate Conventional System Coordinate System Y Axis Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 4
  • 5. Each GUI Component Has its Own Coordinate System (x3, y3) c3’s coordinate (0, 0) Component c3 system (x2, y2) (0, 0) Component c2 c2’s coordinate system (x1, y1) (0, 0) Component c1 c1’s coordinate system Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 5
  • 6. The Graphics Class java.awt.Graphics You can draw strings, +setColor(color: Color): void +setFont(font: Font): void Sets a new color for subsequent drawings. Sets a new font for subsequent drwings. lines, rectangles, ovals, +drawString(s: String, x: int, y: int): void Draws a string starting at point (x, y). +drawLine(x1: int, y1: int, x2: int, y2: int): void Draws a line from (x1, y1) to (x2, y2). arcs, polygons, and +drawRect(x: int, y: int, w: int, h: int): void Draws a rectangle with specified upper-left corner point at (x, y) and width w and height h. polylines, using the +fillRect(x: int, y: int, w: int, h: int): void Draws a filled rectangle with specified upper-left corner point at (x, y) and width w and height h. methods in the Graphics +drawRoundRect(x: int, y: int, w: int, h: int, aw: Draws a round-cornered rectangle with specified arc width aw int, ah: int): void and arc height ah. class. +fillRoundRect(x: int, y: int, w: int, h: int, aw: int, ah: int): void Draws a filled round-cornered rectangle with specified arc width aw and arc height ah. +draw3DRect(x: int, y: int, w: int, h: int, raised: Draws a 3-D rectangle raised above the surface or sunk into the boolean): void surface. +fill3DRect(x: int, y: int, w: int, h: int, raised: Draws a filled 3-D rectangle raised above the surface or sunk boolean): void into the surface. +drawOval(x: int, y: int, w: int, h: int): void Draws an oval bounded by the rectangle specified by the parameters x, y, w, and h. +fillOval(x: int, y: int, w: int, h: int): void Draws a filled oval bounded by the rectangle specified by the parameters x, y, w, and h. +drawArc(x: int, y: int, w: int, h: int, startAngle: Draws an arc conceived as part of an oval bounded by the int, arcAngle: int): void rectangle specified by the parameters x, y, w, and h. +fillArc(x: int, y: int, w: int, h: int, startAngle: Draws a filled arc conceived as part of an oval bounded by the int, arcAngle: int): void rectangle specified by the parameters x, y, w, and h. +drawPolygon(xPoints: int[], yPoints: int[], Draws a closed polygon defined by arrays of x and y nPoints: int): void coordinates. Each pair of (x[i], y[i]) coordinates is a point. +fillPolygon(xPoints: int[], yPoints: int[], Draws a filled polygon defined by arrays of x and y nPoints: int): void coordinates. Each pair of (x[i], y[i]) coordinates is a point. +drawPolygon(g: Polygon): void Draws a closed polygon defined by a Polygon object. +fillPolygon(g: Polygon): void Draws a filled polygon defined by a Polygon object. +drawPolyline(xPoints: int[], yPoints: int[], Draws a polyline defined by arrays of x and y coordinates. nPoints: int): void Each pair of (x[i], y[i]) coordinates is a point. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 6
  • 7. paintComponent Example In order to draw things on a component, you need to define a class that extends JPanel and overrides its paintComponent method to specify what to draw. The first program in this chapter can be rewritten using paintComponent. TestPaintComponent Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 7
  • 8. Drawing Geometric Figures  Drawing Strings  Drawing Lines  Drawing Rectangles  Drawing Ovals  Drawing Arcs  Drawing Polygons Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 8
  • 9. Drawing Strings (0, 0) (getWidth(), 0) (0, 0) (getWidth(), 0) (x1, y1) (x, y) s is display here (x2, y2) (0, getHeight()) (getWidth(), getHeight()) (0, getHeight()) (getWidth(), getHeight()) drawString(String s, int x, int y); drawLine(int x1, int y1, int x2, int y2); Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 9
  • 10. Drawing Rectangles drawRect(int x, int y, int w, int h); fillRect(int x, int y, int w, int h); (x, y) (x, y) h h w w Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 10
  • 11. Drawing Rounded Rectangles drawRoundRect(int x, int y, int w, int h, int aw, int ah); fillRoundRect(int x, int y, int w, int h, int aw, int ah); (x, y) ah/2 aw/2 h w Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 11
  • 12. Drawing Ovals drawOval(int x, int y, int w, int h); fillOval(int x, int y, int w, int h); (x, y) h w Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 12
  • 13. Case Study: The FigurePanel Class This example develops a useful class for displaying various figures. The class enables the user to set the figure type and specify whether the figure is filled, and displays the figure on a panel. javax.swing.JPanel -char token +getToken FigurePanel +setToken +paintComponet LINE, RECTANGLE, +LINE = 1 +mouseClicked ROUND_RECTANGLE, and OVAL are +RECTANGLE = 2 constants. +ROUND_RECTANGLE = 3 +OVAL = 4 -type: int Specifies the figure type (default: 1). -filled: boolean Specifies whether the figure is filled (default: false). +FigurePanel() Creates a default figure panel. +FigurePanel(type: int) Creates a figure panel with the specified type. +FigurePanel(type: int, filled: boolean) Creates a figure panel with the specified type and filled property. +getType(): int Returns the figure type. +setType(type: int): void Sets a new figure type. FigurePanel +isFilled(): boolean Checks whether the figure is filled with a color. +setFilled(filled: boolean): void Sets a new filled property. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 13
  • 14. Test FigurePanel This example develops a useful class for displaying various figures. The class enables the user to set the figure type and specify whether the figure is filled, and displays the figure on a panel. TestFigurePanel Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 14
  • 15. Drawing Arcs drawArc(int x, int y, int w, int h, int angle1, int angle2); fillArc(int x, int y, int w, int h, int angle1, int angle2); Angles are in degree Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 15
  • 16. Drawing Arcs Example DrawArcs Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 16
  • 17. Drawing Polygons and Polylines int[] x = {40, 70, 60, 45, 20}; int[] y = {20, 40, 80, 45, 60}; g.drawPolyline(x, y, x.length); g.drawPolygon(x, y, x.length); (x[0], y[0]) (x[0], y[0]) (x[1], y[1]) (x[1], y[1]) (x[3], y[3]) (x[3], y[3]) (x[4], y[4]) (x[4], y[4]) (x[2], y[2]) (x[2], y[2]) Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 17
  • 18. Drawing Polygons Using the Polygon Class Polygon polygon = new Polygon(); polygon.addPoint(40, 59); polygon.addPoint(40, 100); polygon.addPoint(10, 100); g.drawPolygon(polygon); Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 18
  • 19. Drawing Polygons Example DrawPolygon Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 19
  • 20. Centering Display Using the FontMetrics Class You can display a string at any location in a panel. Can you display it centered? To do so, you need to use the FontMetrics class to measure the exact width and height of the string for a particular font. A FontMetrics can measure the following attributes:  public int getAscent()  public int getHeight()  public int getDescent()  public int stringWidth(String str)  public int getLeading() getLeading() getHeight() getAscent() getDescent() Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 20
  • 21. The FontMetrics Class FontMetrics is an abstract class. To get a FontMetrics object for a specific font, use the following getFontMetrics methods defined in the Graphics class: · public FontMetrics getFontMetrics(Font f) Returns the font metrics of the specified font. · public FontMetrics getFontMetrics() Returns the font metrics of the current font. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 21
  • 22. panel stringWidth getHeight() stringAscent Welcome to Java getWidth() TestCenterMessage Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 22
  • 23. Case Study: MessagePanel javax.swing.JPanel The get and set methods for these data This case study fields are provided in the class, but -char token omitted in the UML diagram develops a useful class +getToken MessagePanel +setToken that displays a message +paintComponet +mouseClicked int -xCoordinate: The x-Coordinate for the message (default 20). in a panel. The class -yCoordinate: int -centered: boolean The y-Coordinate for the message (default 20). Specifies whether the message is displayed centered. enables the user to set -message: String The message to be displayed. the location of the -interval: int The interval to move the message in the panel. message, center the +MessagePanel() +MessagePanel(message: String) Constructs a default message panel. Constructs a message panel with a specified string. message, and move the +moveLeft(): void Moves the message to the left. message with the +moveRight(): void Moves the message to the right. +moveUp(): void Moves the message up. specified interval. +moveDown(): void Moves the message down. MessagePanel TestMessagePanel Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 23
  • 24. Case Study: StillClock javax.swing.JPanel The get and set methods for these data fields are provided in the class, but -char token omitted in the UML diagram +getToken StillClock +setToken +paintComponet -hour: int +mouseClicked The hour in the clock. -minute: int The minute in the clock. -second: int The second in the clock. +StillClock() Constructs a default clock for the current time. +StillClock(hour: int, minute: int, Constructs a clock with a specified time. second: int) +setCurrentTime(): void Sets time to current time. StillClock DisplayClock Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 24
  • 25. Drawing Clock xEnd = xCenter + handLength sin( ) Since there are sixty seconds in one minute, the angle for yEnd = yCenter - handLength cos( ) the second hand is second (2 /60) Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 25
  • 26. Drawing Clock, cont. xEnd = xCenter + handLength sin( ) yEnd = yCenter - handLength cos( ) The position of the minute hand is determined by the minute and second. The exact minute value combined with seconds is minute + second/60. For example, if the time is 3 minutes and 30 seconds. The total minutes are 3.5. Since there are sixty minutes in one hour, the angle for the minute hand is (minute + second/60) (2 /60) Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 26
  • 27. Drawing Clock, cont. xEnd = xCenter + handLength sin( ) yEnd = yCenter - handLength cos( ) Since one circle is divided into twelve hours, the angle for the hour hand is (hour + minute/60 + second/(60 60))) (2 /12) Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 27
  • 28. Displaying Image Icons You learned how to create image icons and display image icons in labels and buttons. For example, the following statements create an image icon and display it in a label: ImageIcon icon = new ImageIcon("image/us.gif"); JLabel jlblImage = new JLabel(imageIcon); An image icon displays a fixed-size image. To display an image in a flexible size, you need to use the java.awt.Image class. An image can be created from an image icon using the getImage() method as follows: Image image = imageIcon.getImage(); Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 28
  • 29. Displaying Images Using a label as an area for displaying images is simple and convenient, but you don't have much control over how the image is displayed. A more flexible way to display images is to use the drawImage method of the Graphics class on a panel. Four versions of the drawImage method are shown here. java.awt.Graphics +drawImage(image: Image, x: int, y: int, Draws the image in a specified location. The image's top-left corner is at bgcolor: Color, observer: (x, y) in the graphics context's coordinate space. Transparent pixels in ImageObserver): void the image are drawn in the specified color bgcolor. The observer is the object on which the image is displayed. The image is cut off if it is larger than the area it is being drawn on. +drawImage(image: Image, x: int, y: int, Same as the preceding method except that it does not specify a background observer: ImageObserver): void color. +drawImage(image: Image, x: int, y: int, Draws a scaled version of the image that can fill all of the available space width: int, height: int, observer: in the specified rectangle. ImageObserver): void +drawImage(image: Image, x: int, y: int, Same as the preceding method except that it provides a solid background width: int, height: int, bgcolor: Color, color behind the image being drawn. observer: ImageObserver): void Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 29
  • 30. Displaying Images Example This example gives the code that displays an image from image/us.gif. The file image/us.gif is under the class directory. The Image from the file is created in the program. The drawImage method displays the image to fill in the whole panel, as shown in the figure. DisplayImage Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 30
  • 31. Case Study: ImageViewer Class Displaying an image is a common task in Java programming. This case study develops a reusable component named ImageViewer that displays an image in a panel. The ImageViewer class contains the properties image, imageFilename, stretched, xCoordinate, and yCoordinate. javax.swing.JPanel The get and set methods for these data fields are provided in the class, but omitted in the UML diagram for brevity. ImageViewer -image: Image Image in the image viewer. -stretched: boolean True if the image is stretched in the viewer. -xCoordinate: int x-coordinate of the upper-left corner of the image in the viewer. -yCoordinate: int y-coordinate of the upper-left corner of the image in the viewer. +ImageViewer() Constructs an image viewer with no image. +ImageViewer(imageFile: String) Constructs an image viewer with the specified image file. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 31
  • 32. ImageView Example This example gives an example that creates six images using the ImageViewer class. SixFlags Run Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 32