SlideShare ist ein Scribd-Unternehmen logo
1 von 32
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
1
Chapter 13 Graphics
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
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.
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.
4
Java Coordinate System
(0, 0) X Axis
Y Axis
(x, y)
x
y
Java Coordinate
System
X Axis
Conventional
Coordinate
System
(0, 0)
Y Axis
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
5
Each GUI Component Has its
Own Coordinate System
(0, 0) Component c2
Component c1
(0, 0)
(0, 0)
(x1, y1)
(x2, y2)
(x3, y3)
Component c3
c3’s coordinate
system
c2’s coordinate
system
c1’s coordinate
system
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
6
The Graphics Class
You can draw strings,
lines, rectangles, ovals,
arcs, polygons, and
polylines, using the
methods in the Graphics
class.
java.awt.Graphics
+setColor(color: Color): void
+setFont(font: Font): void
+drawString(s: String, x: int, y: int): void
+drawLine(x1: int, y1: int, x2: int, y2: int): void
+drawRect(x: int, y: int, w: int, h: int): void
+fillRect(x: int, y: int, w: int, h: int): void
+drawRoundRect(x: int, y: int, w: int, h: int, aw:
int, ah: int): void
+fillRoundRect(x: int, y: int, w: int, h: int, aw:
int, ah: int): void
+draw3DRect(x: int, y: int, w: int, h: int, raised:
boolean): void
+fill3DRect(x: int, y: int, w: int, h: int, raised:
boolean): void
+drawOval(x: int, y: int, w: int, h: int): void
+fillOval(x: int, y: int, w: int, h: int): void
+drawArc(x: int, y: int, w: int, h: int, startAngle:
int, arcAngle: int): void
+fillArc(x: int, y: int, w: int, h: int, startAngle:
int, arcAngle: int): void
+drawPolygon(xPoints: int[], yPoints: int[],
nPoints: int): void
+fillPolygon(xPoints: int[], yPoints: int[],
nPoints: int): void
+drawPolygon(g: Polygon): void
+fillPolygon(g: Polygon): void
+drawPolyline(xPoints: int[], yPoints: int[],
nPoints: int): void
Sets a new color for subsequent drawings.
Sets a new font for subsequent drwings.
Draws a string starting at point (x, y).
Draws a line from (x1, y1) to (x2, y2).
Draws a rectangle with specified upper-left corner point at (x,
y) and width w and height h.
Draws a filled rectangle with specified upper-left corner point
at (x, y) and width w and height h.
Draws a round-cornered rectangle with specified arc width aw
and arc height ah.
Draws a filled round-cornered rectangle with specified arc
width aw and arc height ah.
Draws a 3-D rectangle raised above the surface or sunk into the
surface.
Draws a filled 3-D rectangle raised above the surface or sunk
into the surface.
Draws an oval bounded by the rectangle specified by the
parameters x, y, w, and h.
Draws a filled oval bounded by the rectangle specified by the
parameters x, y, w, and h.
Draws an arc conceived as part of an oval bounded by the
rectangle specified by the parameters x, y, w, and h.
Draws a filled arc conceived as part of an oval bounded by the
rectangle specified by the parameters x, y, w, and h.
Draws a closed polygon defined by arrays of x and y
coordinates. Each pair of (x[i], y[i]) coordinates is a point.
Draws a filled polygon defined by arrays of x and y
coordinates. Each pair of (x[i], y[i]) coordinates is a point.
Draws a closed polygon defined by a Polygon object.
Draws a filled polygon defined by a Polygon object.
Draws a polyline defined by arrays of x and y coordinates.
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.
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.
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.
9
Drawing Strings
(0, 0) (getWidth(), 0)
(getWidth(), getHeight())
(0, getHeight())
(x, y) s is display here
(0, 0) (getWidth(), 0)
(getWidth(), getHeight())
(0, getHeight())
(x1, y1)
(x2, y2)
drawLine(int x1, int y1, int x2, int y2);
drawString(String s, int x, int y);
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
10
Drawing Rectangles
drawRect(int x, int y, int w, int h);
fillRect(int x, int y, int w, int h);
(x, y)
w
h
(x, y)
w
h
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
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)
w
h
ah/2
aw/2
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
12
Drawing Ovals
drawOval(int x, int y, int w, int h);
fillOval(int x, int y, int w, int h);
(x, y)
w
h
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
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.
FigurePanel
+LINE = 1
+RECTANGLE = 2
+ROUND_RECTANGLE = 3
+OVAL = 4
-type: int
-filled: boolean
+FigurePanel()
+FigurePanel(type: int)
+FigurePanel(type: int, filled: boolean)
+getType(): int
+setType(type: int): void
+isFilled(): boolean
+setFilled(filled: boolean): void
javax.swing.JPanel
-char token
+getToken
+setToken
+paintComponet
+mouseClicked
LINE, RECTANGLE,
ROUND_RECTANGLE, and OVAL are
constants.
Specifies the figure type (default: 1).
Specifies whether the figure is filled (default: false).
Creates a default figure panel.
Creates a figure panel with the specified type.
Creates a figure panel with the specified type and filled property.
Returns the figure type.
Sets a new figure type.
Checks whether the figure is filled with a color.
Sets a new filled property.
FigurePanel
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
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.
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.
16
Drawing Arcs Example
DrawArcs Run
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
17
Drawing Polygons and Polylines
int[] x = {40, 70, 60, 45, 20};
int[] y = {20, 40, 80, 45, 60};
g.drawPolygon(x, y, x.length);
(x[0], y[0])
(x[1], y[1])
(x[2], y[2])
(x[3], y[3])
(x[4], y[4])
g.drawPolyline(x, y, x.length);
(x[0], y[0])
(x[1], y[1])
(x[2], y[2])
(x[3], y[3])
(x[4], y[4])
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
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.
19
Drawing Polygons Example
DrawPolygon Run
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
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 getDescent()
 public int getLeading()
getAscent()
getLeading()
getDescent()
getHeight()
 public int getHeight()
 public int stringWidth(String str)
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
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.
22
Welcome to Java
stringWidth
stringAscent
getHeight()
getWidth()
panel
TestCenterMessage Run
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
23
Case Study: MessagePanel
MessagePanel
-xCoordinate: int
-yCoordinate: int
-centered: boolean
-message: String
-interval: int
+MessagePanel()
+MessagePanel(message: String)
+moveLeft(): void
+moveRight(): void
+moveUp(): void
+moveDown(): void
javax.swing.JPanel
-char token
+getToken
+setToken
+paintComponet
+mouseClicked
The get and set methods for these data
fields are provided in the class, but
omitted in the UML diagram
The x-Coordinate for the message (default 20).
The y-Coordinate for the message (default 20).
Specifies whether the message is displayed centered.
The message to be displayed.
The interval to move the message in the panel.
Constructs a default message panel.
Constructs a message panel with a specified string.
Moves the message to the left.
Moves the message to the right.
Moves the message up.
Moves the message down.
MessagePanel Run
This case study
develops a useful class
that displays a message
in a panel. The class
enables the user to set
the location of the
message, center the
message, and move the
message with the
specified interval.
TestMessagePanel
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
24
Case Study: StillClock
DisplayClock Run
StillClock
StillClock
-hour: int
-minute: int
-second: int
+StillClock()
+StillClock(hour: int, minute: int,
second: int)
+setCurrentTime(): void
javax.swing.JPanel
-char token
+getToken
+setToken
+paintComponet
+mouseClicked
The get and set methods for these data
fields are provided in the class, but
omitted in the UML diagram
The hour in the clock.
The minute in the clock.
The second in the clock.
Constructs a default clock for the current time.
Constructs a clock with a specified time.
Sets time to current time.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
25
Drawing Clock
xEnd = xCenter + handLength  sin()
yEnd = yCenter - handLength  cos()
Since there are sixty seconds
in one minute, the angle for
the second hand is
second  (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()
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.
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.
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.
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,
bgcolor: Color, observer:
ImageObserver): void
+drawImage(image: Image, x: int, y: int,
observer: ImageObserver): void
+drawImage(image: Image, x: int, y: int,
width: int, height: int, observer:
ImageObserver): void
+drawImage(image: Image, x: int, y: int,
width: int, height: int, bgcolor: Color,
observer: ImageObserver): void
Draws the image in a specified location. The image's top-left corner is at
(x, y) in the graphics context's coordinate space. Transparent pixels in
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.
Same as the preceding method except that it does not specify a background
color.
Draws a scaled version of the image that can fill all of the available space
in the specified rectangle.
Same as the preceding method except that it provides a solid background
color behind the image being drawn.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
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.
Run
DisplayImage
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
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.
ImageViewer
-image: Image
-stretched: boolean
-xCoordinate: int
-yCoordinate: int
+ImageViewer()
+ImageViewer(imageFile: String)
javax.swing.JPanel
Image in the image viewer.
True if the image is stretched in the viewer.
x-coordinate of the upper-left corner of the image in the viewer.
y-coordinate of the upper-left corner of the image in the viewer.
Constructs an image viewer with no image.
Constructs an image viewer with the specified image file.
The get and set methods for these data
fields are provided in the class, but
omitted in the UML diagram for brevity.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved.
32
ImageView Example
This example gives an example that creates six images using the
ImageViewer class.
Run
SixFlags

Weitere ähnliche Inhalte

Was ist angesagt?

Java cơ bản java co ban
Java cơ bản java co ban Java cơ bản java co ban
Java cơ bản java co ban ifis
 
Informatics Practices (new) solution CBSE 2021, Compartment, improvement ex...
Informatics Practices (new) solution CBSE  2021, Compartment,  improvement ex...Informatics Practices (new) solution CBSE  2021, Compartment,  improvement ex...
Informatics Practices (new) solution CBSE 2021, Compartment, improvement ex...FarhanAhmade
 
Question Paper Code 065 informatic Practice New CBSE - 2021
Question Paper Code 065 informatic Practice New CBSE - 2021 Question Paper Code 065 informatic Practice New CBSE - 2021
Question Paper Code 065 informatic Practice New CBSE - 2021 FarhanAhmade
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and SetIntro C# Book
 
GATE Computer Science Solved Paper 2004
GATE Computer Science Solved Paper 2004GATE Computer Science Solved Paper 2004
GATE Computer Science Solved Paper 2004Rohit Garg
 
Object Oriented Programming - Value Types & Reference Types
Object Oriented Programming - Value Types & Reference TypesObject Oriented Programming - Value Types & Reference Types
Object Oriented Programming - Value Types & Reference TypesDudy Ali
 
Designing Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.ProtoDesigning Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.ProtoJoel Falcou
 
Approximation Data Structures for Streaming Applications
Approximation Data Structures for Streaming ApplicationsApproximation Data Structures for Streaming Applications
Approximation Data Structures for Streaming ApplicationsDebasish Ghosh
 
Cvpr2010 open source vision software, intro and training part-iii introduct...
Cvpr2010 open source vision software, intro and training   part-iii introduct...Cvpr2010 open source vision software, intro and training   part-iii introduct...
Cvpr2010 open source vision software, intro and training part-iii introduct...zukun
 
Introduction to Gura Programming Language
Introduction to Gura Programming LanguageIntroduction to Gura Programming Language
Introduction to Gura Programming LanguageYutaka Saito
 
Category Theory for Mortal Programmers
Category Theory for Mortal ProgrammersCategory Theory for Mortal Programmers
Category Theory for Mortal ProgrammersStephan February
 
Output Units and Cost Function in FNN
Output Units and Cost Function in FNNOutput Units and Cost Function in FNN
Output Units and Cost Function in FNNLin JiaMing
 
Gaussian Processes: Applications in Machine Learning
Gaussian Processes: Applications in Machine LearningGaussian Processes: Applications in Machine Learning
Gaussian Processes: Applications in Machine Learningbutest
 
Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++Anton Kolotaev
 

Was ist angesagt? (20)

Java cơ bản java co ban
Java cơ bản java co ban Java cơ bản java co ban
Java cơ bản java co ban
 
Informatics Practices (new) solution CBSE 2021, Compartment, improvement ex...
Informatics Practices (new) solution CBSE  2021, Compartment,  improvement ex...Informatics Practices (new) solution CBSE  2021, Compartment,  improvement ex...
Informatics Practices (new) solution CBSE 2021, Compartment, improvement ex...
 
Array
ArrayArray
Array
 
Question Paper Code 065 informatic Practice New CBSE - 2021
Question Paper Code 065 informatic Practice New CBSE - 2021 Question Paper Code 065 informatic Practice New CBSE - 2021
Question Paper Code 065 informatic Practice New CBSE - 2021
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
 
GATE Computer Science Solved Paper 2004
GATE Computer Science Solved Paper 2004GATE Computer Science Solved Paper 2004
GATE Computer Science Solved Paper 2004
 
Midterm sols
Midterm solsMidterm sols
Midterm sols
 
Midterm
MidtermMidterm
Midterm
 
Object Oriented Programming - Value Types & Reference Types
Object Oriented Programming - Value Types & Reference TypesObject Oriented Programming - Value Types & Reference Types
Object Oriented Programming - Value Types & Reference Types
 
Designing Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.ProtoDesigning Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.Proto
 
Computer Programming- Lecture 8
Computer Programming- Lecture 8Computer Programming- Lecture 8
Computer Programming- Lecture 8
 
ARIC Team Seminar
ARIC Team SeminarARIC Team Seminar
ARIC Team Seminar
 
Approximation Data Structures for Streaming Applications
Approximation Data Structures for Streaming ApplicationsApproximation Data Structures for Streaming Applications
Approximation Data Structures for Streaming Applications
 
Cvpr2010 open source vision software, intro and training part-iii introduct...
Cvpr2010 open source vision software, intro and training   part-iii introduct...Cvpr2010 open source vision software, intro and training   part-iii introduct...
Cvpr2010 open source vision software, intro and training part-iii introduct...
 
Introduction to Gura Programming Language
Introduction to Gura Programming LanguageIntroduction to Gura Programming Language
Introduction to Gura Programming Language
 
Category Theory for Mortal Programmers
Category Theory for Mortal ProgrammersCategory Theory for Mortal Programmers
Category Theory for Mortal Programmers
 
Output Units and Cost Function in FNN
Output Units and Cost Function in FNNOutput Units and Cost Function in FNN
Output Units and Cost Function in FNN
 
C++ Templates 2
C++ Templates 2C++ Templates 2
C++ Templates 2
 
Gaussian Processes: Applications in Machine Learning
Gaussian Processes: Applications in Machine LearningGaussian Processes: Applications in Machine Learning
Gaussian Processes: Applications in Machine Learning
 
Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++Generic programming and concepts that should be in C++
Generic programming and concepts that should be in C++
 

Andere mochten auch

bai giang java co ban - java cơ bản - bai 1
bai giang java co ban - java cơ bản - bai 1bai giang java co ban - java cơ bản - bai 1
bai giang java co ban - java cơ bản - bai 1ifis
 
kg0000931 Chapter 1 introduction to computers, programs part ia
kg0000931 Chapter 1 introduction to computers, programs part ia kg0000931 Chapter 1 introduction to computers, programs part ia
kg0000931 Chapter 1 introduction to computers, programs part ia kg0000931
 
9781285852744 ppt ch02
9781285852744 ppt ch029781285852744 ppt ch02
9781285852744 ppt ch02Terry Yoast
 
문과생 대상 파이썬을 활용한 데이터 분석 강의
문과생 대상 파이썬을 활용한 데이터 분석 강의문과생 대상 파이썬을 활용한 데이터 분석 강의
문과생 대상 파이썬을 활용한 데이터 분석 강의Kwangyoun Jung
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Languagejaimefrozr
 
Exception handling
Exception handlingException handling
Exception handlingRaja Sekhar
 
String handling session 5
String handling session 5String handling session 5
String handling session 5Raja Sekhar
 

Andere mochten auch (18)

11slide
11slide11slide
11slide
 
08slide
08slide08slide
08slide
 
12slide
12slide12slide
12slide
 
01slide
01slide01slide
01slide
 
03slide
03slide03slide
03slide
 
04slide
04slide04slide
04slide
 
10slide
10slide10slide
10slide
 
JavaYDL5
JavaYDL5JavaYDL5
JavaYDL5
 
JavaYDL18
JavaYDL18JavaYDL18
JavaYDL18
 
bai giang java co ban - java cơ bản - bai 1
bai giang java co ban - java cơ bản - bai 1bai giang java co ban - java cơ bản - bai 1
bai giang java co ban - java cơ bản - bai 1
 
01slide
01slide01slide
01slide
 
kg0000931 Chapter 1 introduction to computers, programs part ia
kg0000931 Chapter 1 introduction to computers, programs part ia kg0000931 Chapter 1 introduction to computers, programs part ia
kg0000931 Chapter 1 introduction to computers, programs part ia
 
07slide
07slide07slide
07slide
 
9781285852744 ppt ch02
9781285852744 ppt ch029781285852744 ppt ch02
9781285852744 ppt ch02
 
문과생 대상 파이썬을 활용한 데이터 분석 강의
문과생 대상 파이썬을 활용한 데이터 분석 강의문과생 대상 파이썬을 활용한 데이터 분석 강의
문과생 대상 파이썬을 활용한 데이터 분석 강의
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
Exception handling
Exception handlingException handling
Exception handling
 
String handling session 5
String handling session 5String handling session 5
String handling session 5
 

Ähnlich wie 13slide graphics

JavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.pptJavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.pptMohammedNouh7
 
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 1Philip Schwarz
 
graphics programming in java
graphics programming in javagraphics programming in java
graphics programming in javaAbinaya B
 
Basic Graphics in Java
Basic Graphics in JavaBasic Graphics in Java
Basic Graphics in JavaPrakash Kumar
 
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 1bPhilip Schwarz
 
ImplementDijkstra’s algorithm using the graph class you implemente.pdf
ImplementDijkstra’s algorithm using the graph class you implemente.pdfImplementDijkstra’s algorithm using the graph class you implemente.pdf
ImplementDijkstra’s algorithm using the graph class you implemente.pdfgopalk44
 
Displaying information within a window.68
Displaying information within a window.68Displaying information within a window.68
Displaying information within a window.68myrajendra
 
Language Language Models (in 2023) - OpenAI
Language Language Models (in 2023) - OpenAILanguage Language Models (in 2023) - OpenAI
Language Language Models (in 2023) - OpenAISamuelButler15
 
U5 JAVA.pptx
U5 JAVA.pptxU5 JAVA.pptx
U5 JAVA.pptxmadan r
 
Numerical analysis
Numerical analysisNumerical analysis
Numerical analysisVishal Singh
 
Chapter 1: Linear Regression
Chapter 1: Linear RegressionChapter 1: Linear Regression
Chapter 1: Linear RegressionAkmelSyed
 
Java applet handouts
Java applet handoutsJava applet handouts
Java applet handoutsiamkim
 
COMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALCOMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALVivek Kumar Sinha
 
Dip 5 mathematical preliminaries
Dip 5 mathematical preliminariesDip 5 mathematical preliminaries
Dip 5 mathematical preliminariesManas Mantri
 

Ähnlich wie 13slide graphics (20)

JavaYDL13
JavaYDL13JavaYDL13
JavaYDL13
 
JavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.pptJavaProgramming 17321_CS202-Chapter8.ppt
JavaProgramming 17321_CS202-Chapter8.ppt
 
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
 
graphics programming in java
graphics programming in javagraphics programming in java
graphics programming in java
 
Basic Graphics in Java
Basic Graphics in JavaBasic Graphics in Java
Basic Graphics in Java
 
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
 
C++ Inheritance
C++ InheritanceC++ Inheritance
C++ Inheritance
 
java graphics
java graphicsjava graphics
java graphics
 
ImplementDijkstra’s algorithm using the graph class you implemente.pdf
ImplementDijkstra’s algorithm using the graph class you implemente.pdfImplementDijkstra’s algorithm using the graph class you implemente.pdf
ImplementDijkstra’s algorithm using the graph class you implemente.pdf
 
662305 10
662305 10662305 10
662305 10
 
Displaying information within a window.68
Displaying information within a window.68Displaying information within a window.68
Displaying information within a window.68
 
Language Language Models (in 2023) - OpenAI
Language Language Models (in 2023) - OpenAILanguage Language Models (in 2023) - OpenAI
Language Language Models (in 2023) - OpenAI
 
U5 JAVA.pptx
U5 JAVA.pptxU5 JAVA.pptx
U5 JAVA.pptx
 
CP Handout#9
CP Handout#9CP Handout#9
CP Handout#9
 
Numerical analysis
Numerical analysisNumerical analysis
Numerical analysis
 
Chapter 1: Linear Regression
Chapter 1: Linear RegressionChapter 1: Linear Regression
Chapter 1: Linear Regression
 
Applets
AppletsApplets
Applets
 
Java applet handouts
Java applet handoutsJava applet handouts
Java applet handouts
 
COMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALCOMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUAL
 
Dip 5 mathematical preliminaries
Dip 5 mathematical preliminariesDip 5 mathematical preliminaries
Dip 5 mathematical preliminaries
 

Kürzlich hochgeladen

Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 

Kürzlich hochgeladen (20)

E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 

13slide graphics

  • 1. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 13 Graphics
  • 2. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 2 Motivations If you want to draw shapes such as a bar chart, a clock, or a stop sign, how do you do it?
  • 3. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 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).
  • 4. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 4 Java Coordinate System (0, 0) X Axis Y Axis (x, y) x y Java Coordinate System X Axis Conventional Coordinate System (0, 0) Y Axis
  • 5. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 5 Each GUI Component Has its Own Coordinate System (0, 0) Component c2 Component c1 (0, 0) (0, 0) (x1, y1) (x2, y2) (x3, y3) Component c3 c3’s coordinate system c2’s coordinate system c1’s coordinate system
  • 6. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 6 The Graphics Class You can draw strings, lines, rectangles, ovals, arcs, polygons, and polylines, using the methods in the Graphics class. java.awt.Graphics +setColor(color: Color): void +setFont(font: Font): void +drawString(s: String, x: int, y: int): void +drawLine(x1: int, y1: int, x2: int, y2: int): void +drawRect(x: int, y: int, w: int, h: int): void +fillRect(x: int, y: int, w: int, h: int): void +drawRoundRect(x: int, y: int, w: int, h: int, aw: int, ah: int): void +fillRoundRect(x: int, y: int, w: int, h: int, aw: int, ah: int): void +draw3DRect(x: int, y: int, w: int, h: int, raised: boolean): void +fill3DRect(x: int, y: int, w: int, h: int, raised: boolean): void +drawOval(x: int, y: int, w: int, h: int): void +fillOval(x: int, y: int, w: int, h: int): void +drawArc(x: int, y: int, w: int, h: int, startAngle: int, arcAngle: int): void +fillArc(x: int, y: int, w: int, h: int, startAngle: int, arcAngle: int): void +drawPolygon(xPoints: int[], yPoints: int[], nPoints: int): void +fillPolygon(xPoints: int[], yPoints: int[], nPoints: int): void +drawPolygon(g: Polygon): void +fillPolygon(g: Polygon): void +drawPolyline(xPoints: int[], yPoints: int[], nPoints: int): void Sets a new color for subsequent drawings. Sets a new font for subsequent drwings. Draws a string starting at point (x, y). Draws a line from (x1, y1) to (x2, y2). Draws a rectangle with specified upper-left corner point at (x, y) and width w and height h. Draws a filled rectangle with specified upper-left corner point at (x, y) and width w and height h. Draws a round-cornered rectangle with specified arc width aw and arc height ah. Draws a filled round-cornered rectangle with specified arc width aw and arc height ah. Draws a 3-D rectangle raised above the surface or sunk into the surface. Draws a filled 3-D rectangle raised above the surface or sunk into the surface. Draws an oval bounded by the rectangle specified by the parameters x, y, w, and h. Draws a filled oval bounded by the rectangle specified by the parameters x, y, w, and h. Draws an arc conceived as part of an oval bounded by the rectangle specified by the parameters x, y, w, and h. Draws a filled arc conceived as part of an oval bounded by the rectangle specified by the parameters x, y, w, and h. Draws a closed polygon defined by arrays of x and y coordinates. Each pair of (x[i], y[i]) coordinates is a point. Draws a filled polygon defined by arrays of x and y coordinates. Each pair of (x[i], y[i]) coordinates is a point. Draws a closed polygon defined by a Polygon object. Draws a filled polygon defined by a Polygon object. Draws a polyline defined by arrays of x and y coordinates. Each pair of (x[i], y[i]) coordinates is a point.
  • 7. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 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
  • 8. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 8 Drawing Geometric Figures  Drawing Strings  Drawing Lines  Drawing Rectangles  Drawing Ovals  Drawing Arcs  Drawing Polygons
  • 9. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 9 Drawing Strings (0, 0) (getWidth(), 0) (getWidth(), getHeight()) (0, getHeight()) (x, y) s is display here (0, 0) (getWidth(), 0) (getWidth(), getHeight()) (0, getHeight()) (x1, y1) (x2, y2) drawLine(int x1, int y1, int x2, int y2); drawString(String s, int x, int y);
  • 10. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 10 Drawing Rectangles drawRect(int x, int y, int w, int h); fillRect(int x, int y, int w, int h); (x, y) w h (x, y) w h
  • 11. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 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) w h ah/2 aw/2
  • 12. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 12 Drawing Ovals drawOval(int x, int y, int w, int h); fillOval(int x, int y, int w, int h); (x, y) w h
  • 13. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 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. FigurePanel +LINE = 1 +RECTANGLE = 2 +ROUND_RECTANGLE = 3 +OVAL = 4 -type: int -filled: boolean +FigurePanel() +FigurePanel(type: int) +FigurePanel(type: int, filled: boolean) +getType(): int +setType(type: int): void +isFilled(): boolean +setFilled(filled: boolean): void javax.swing.JPanel -char token +getToken +setToken +paintComponet +mouseClicked LINE, RECTANGLE, ROUND_RECTANGLE, and OVAL are constants. Specifies the figure type (default: 1). Specifies whether the figure is filled (default: false). Creates a default figure panel. Creates a figure panel with the specified type. Creates a figure panel with the specified type and filled property. Returns the figure type. Sets a new figure type. Checks whether the figure is filled with a color. Sets a new filled property. FigurePanel
  • 14. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 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
  • 15. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 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
  • 16. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 16 Drawing Arcs Example DrawArcs Run
  • 17. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 17 Drawing Polygons and Polylines int[] x = {40, 70, 60, 45, 20}; int[] y = {20, 40, 80, 45, 60}; g.drawPolygon(x, y, x.length); (x[0], y[0]) (x[1], y[1]) (x[2], y[2]) (x[3], y[3]) (x[4], y[4]) g.drawPolyline(x, y, x.length); (x[0], y[0]) (x[1], y[1]) (x[2], y[2]) (x[3], y[3]) (x[4], y[4])
  • 18. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 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);
  • 19. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 19 Drawing Polygons Example DrawPolygon Run
  • 20. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 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 getDescent()  public int getLeading() getAscent() getLeading() getDescent() getHeight()  public int getHeight()  public int stringWidth(String str)
  • 21. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 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.
  • 22. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 22 Welcome to Java stringWidth stringAscent getHeight() getWidth() panel TestCenterMessage Run
  • 23. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 23 Case Study: MessagePanel MessagePanel -xCoordinate: int -yCoordinate: int -centered: boolean -message: String -interval: int +MessagePanel() +MessagePanel(message: String) +moveLeft(): void +moveRight(): void +moveUp(): void +moveDown(): void javax.swing.JPanel -char token +getToken +setToken +paintComponet +mouseClicked The get and set methods for these data fields are provided in the class, but omitted in the UML diagram The x-Coordinate for the message (default 20). The y-Coordinate for the message (default 20). Specifies whether the message is displayed centered. The message to be displayed. The interval to move the message in the panel. Constructs a default message panel. Constructs a message panel with a specified string. Moves the message to the left. Moves the message to the right. Moves the message up. Moves the message down. MessagePanel Run This case study develops a useful class that displays a message in a panel. The class enables the user to set the location of the message, center the message, and move the message with the specified interval. TestMessagePanel
  • 24. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 24 Case Study: StillClock DisplayClock Run StillClock StillClock -hour: int -minute: int -second: int +StillClock() +StillClock(hour: int, minute: int, second: int) +setCurrentTime(): void javax.swing.JPanel -char token +getToken +setToken +paintComponet +mouseClicked The get and set methods for these data fields are provided in the class, but omitted in the UML diagram The hour in the clock. The minute in the clock. The second in the clock. Constructs a default clock for the current time. Constructs a clock with a specified time. Sets time to current time.
  • 25. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 25 Drawing Clock xEnd = xCenter + handLength  sin() yEnd = yCenter - handLength  cos() Since there are sixty seconds in one minute, the angle for the second hand is second  (2/60)
  • 26. 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() 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)
  • 27. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 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)
  • 28. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 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();
  • 29. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 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, bgcolor: Color, observer: ImageObserver): void +drawImage(image: Image, x: int, y: int, observer: ImageObserver): void +drawImage(image: Image, x: int, y: int, width: int, height: int, observer: ImageObserver): void +drawImage(image: Image, x: int, y: int, width: int, height: int, bgcolor: Color, observer: ImageObserver): void Draws the image in a specified location. The image's top-left corner is at (x, y) in the graphics context's coordinate space. Transparent pixels in 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. Same as the preceding method except that it does not specify a background color. Draws a scaled version of the image that can fill all of the available space in the specified rectangle. Same as the preceding method except that it provides a solid background color behind the image being drawn.
  • 30. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 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. Run DisplayImage
  • 31. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 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. ImageViewer -image: Image -stretched: boolean -xCoordinate: int -yCoordinate: int +ImageViewer() +ImageViewer(imageFile: String) javax.swing.JPanel Image in the image viewer. True if the image is stretched in the viewer. x-coordinate of the upper-left corner of the image in the viewer. y-coordinate of the upper-left corner of the image in the viewer. Constructs an image viewer with no image. Constructs an image viewer with the specified image file. The get and set methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.
  • 32. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 32 ImageView Example This example gives an example that creates six images using the ImageViewer class. Run SixFlags