Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Java Programming
Graphical Objects
Arash Habibi Lashkari
Ph.D. Candidate of UTM University
Kuala Lumpur, Malaysia
All Rights Reserved © 2010,
2010, www.ahlashkari.com
Intro
Graphic operations are supported by
package java.awt.
Facilities include: drawing different types of
colored shapes,
p
displaying
p y g images,
g
animation
www.ahlashkari.com
2
Graphics and Graphics2D classes
Package java.awt provides the class Graphics
An instant of Graphics
p
object
j
contains information
to perform graphic operations
Graphic operations are executed by sending specific
messages to graphic objects,
objects including:
drawString(String, int, int)
drawRect(int,
drawRect(int int,
int int,
int int)
setColor(Color)
setFont(Font)
(
)
www.ahlashkari.com
3
Graphics2D Class
Java 1.2 provides the class Graphics2D
It is a subclass of Graphics.
Graphics
Contains extended fitures which are more
sophisticated.
sophisticated
method paint() still receive Graphics object
as parameter
parameter.
www.ahlashkari.com
4
Class Graphics2D
import javax.swing.*;
import
p
jjava.awt.*;
public class Graphic_01 extends JApplet {
Staring
St
i
att
location (10,20)
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawString(“Using Graphics2d class", 10, 20);
}
}
Cast object g so that we may use
Ch
Characteristics
t i ti off Graphics2d
G
hi 2d
www.ahlashkari.com
5
Coordinate System
y
Every Container object has its own coordinate
system.
Any point in a container may be represented as
(x, y) coordinate.
In AWT, value of x and y for (x, y) coordinate
must be of type integer.
www.ahlashkari.com
6
Coordinate System
0
+x
X axell
0
((x,, y)
+y
Y axel
www.ahlashkari.com
7
Color and Text
To display a text s at coordinate (x
(x, y),
y) message
:
drawString(String s, int x, int y) can be sent to object
Graphics.
g2d.drawString(“How are you?", 10, 50);
“How are you”
at location (10,50)
www.ahlashkari.com
8
Color and Text
By default,
default object Graphics is set to draw text
in black. For other colours, we need to send
g setColor(Color)
(
) to the object
j
first.
message
g2d.setColor(Color.red);
g2d.drawString(“How are you?", 10, 50);
www.ahlashkari.com
9
Class Color
There are several colours already defined in the
library:
g
y
Color.white
Color.lightGray
Color.gray
Color.darkGray
Color.black
Color.red
Color.pink
Color.blue
Color.orange
Color.yellow
Color.green
Color.magenta
Color.cyan
www.ahlashkari.com
10
Class FontMetrics
The Component class has a method getFontMetrics(Font)
which returns object FontMetrics for a specific font.
Font font = new Font("TimesRoman", Font.PLAIN, 14);
FontMetrics fm = getFontMetrics(font);
www.ahlashkari.com
11
Class FontMetrics
leading
g
height
e b k p
www.ahlashkari.com
ascent
descent
baseline
12
Class FontMetrics
leading
height
g
ebkp
ascent
descent
baseline
Amongst the
A
h methods/messages
h d /
that
h can b
be sent to object
bj
FontMetrics:
int stringWidth(String str)
g str for a specific
p
font
Get the width of string
getAscent()
Get the ascent value for a specific font
getDescent()
Get the descent value for a specific font
int getHeight()
Get the height value for a specific font
www.ahlashkari.com
13
Class FontMetrics
leading
height
ebkp
ascent
descent
baseline
int getLeading()
Get the leading value for a specific font
iintt getMaxAscent()
tM A
t()
Get the maximum ascent value (i.e. ascent + leading) for a
specific font
iintt getMaxDescent()
tM D
t()
Get the maximum descent value(i.e. descent + leading) for a
specific font
www.ahlashkari.com
14
Example..
import java
java.awt.
awt *;;
import javax.swing.*;
Get str1width
public class FontMetric extends JApplet {
public void paint(Graphics g) {
Graphics g2d = (Graphics2D) g;
Font font = new Font("SanSerif", Font.PLAIN, 14);
FontMetrics metric = g
getFontMetrics(font);
(
);
}
}
Draw luck at
Location after str1
String str1 = "Good ";
int str1width = metric.stringWidth(str1);
g2d.setFont(font);
g2d.setColor(Color.blue);
g2d.drawString(str1, 50, 50);
g2d.setFont(new Font("Serif", Font.BOLD+Font.ITALIC, 24));
g2d.setColor(Color.red);
g2d.drawString("Luck",
2d d
St i ("L k" 50+str1width,
50+ t 1 idth 50);
50)
www.ahlashkari.com
15
Example
www.ahlashkari.com
16
Drawing
g Basic Shapes
p
Java2D provides a Shape class hierarchy
which contains several classes for different
shapes. Some of the subclasses of class
Shape:
Line2D,
Li
2D
Rectangle2D, RoundRectangle2D,
Ellipse2D Arc2D
Ellipse2D,
Arc2D, QuadCurve2D
QuadCurve2D,
CubicCurve2D, GeneralPath.
www.ahlashkari.com
17
Drawing
g Basic Shapes
p
Following messages can be sent to object
Graphics2D to draw and colour the object
Shape:
void draw(Shape s)
Draw the frame of shape s
void fill(Shape s)
Colour the inner area of shape s
www.ahlashkari.com
18
Lines
A line can be represented by object Line2D.Float or
Line2D.Double.
B th classes
Both
l
Li 2D Fl t and
Line2D.Float
d Line2D.Double
Li 2D D bl are
inner classes of class Line2D.
For Line2D.Float, the end point is of type float
Where as for Line2D.Double, the end point is of type
double.
www.ahlashkari.com
19
Lines
To create an object Line2D with end point
(5, 10) and (25, 40):
new Line2D.Float(5, 10, 25, 40) OR
new Line2D.Double(5, 10, 25, 40)
•Object Line2D can be created without any
parameter. In this case, the end point are
((0,0)) and ((0, 0))
www.ahlashkari.com
20
Lines
The following messages are understood by
object Line2D:
setLine(float x1,
x1 float y1,
y1 float x2,
x2 float y2)
setLine(double x1, double y1, double x2,
double y2)
Will set the end point coordinate to (x1, y1)
and (x2, y2)
www.ahlashkari.com
21
Example
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
public class LineDemo1 extends JApplet {
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
Line2D Double line = new Line2D.Double(10,
Line2D.Double
Line2D Double(10 10,
10 100,
100 10);
g2d.draw(line);
// or g
g2d.draw(new
(
Line2D.Double(10,
(
10, 100, 10));
))
}
}
(10,10)
(100,10)
www.ahlashkari.com
22
Example..
p
import
p
jjava.awt.*;
import javax.swing.*;
import java.awt.geom.*;
public class LineDemo2 extends JApplet {
private static final int distance = 10;
public void paint(Graphics g) {
Line2D.Double line = new Line2D.Double();
Graphics2D
p
g2d = ((Graphics2D)
g
p
) g;
g2d.setColor(Color.blue);
int appletWidth = getSize().width;
int appletHeight = getSize().height;
}
}
Draw vertical line
for (int i=0; i < appletHeight; i += distance) {
line.setLine(0, i, appletWidth, i);
g2d.draw(line);}
for (int i=0; i < appletWidth; i += distance) {
line.setLine(i, 0, i, appletHeight);
Draw horizontal line
g2d.draw(line);}
www.ahlashkari.com
23
Example..
www.ahlashkari.com
24
Line Thickness
The thickness of a drawn line can be set by
replacing the default object Stroke for object
Graphics2D with a new object Stroke
Graphics2D g2d = (Graphics2D) g;
Line2D.Double line = new Line2D.Double(10, 10, 100, 10);
g2d.draw(line);
g2d.setStroke(new
g
d.se S o e( e BasicStroke(10));
as cS o e( 0));
line = new Line2D.Double(10, 30, 100, 30);
g2d.draw(line);
www.ahlashkari.com
25
Example
import java.awt.*;
import javax.swing.*;
j
g
import java.awt.geom.*;
public class LineDemo3 extends JApplet {
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
Line2D Double line = new Line2D
Line2D.Double
Line2D.Double(10,
Double(10 10,
10 100,
100 10);
g2d.draw(line);
g2d.setStroke(new BasicStroke(10));
line = new Line2D
Line2D.Double(10,
Double(10 30,
30 100,
100 30);
g2d.draw(line);
line = new Line2D.Double(0, 0,0, 0);
g
g2d.setColor(Color.blue);
(
)
g2d.draw(line);
}
}
www.ahlashkari.com
26
Third line is a point at (0,0) with
width 10, and coloured blue
Line WidthThickness
line = new Line2D.Double(0, 0,0,0);
g2d.setColor(Color.blue);
2d
C l (C l bl )
g2d.draw(blue);
First line
Line2D.Double line = new
Line2D.Double(10, 10, 100, 10);
g2d.draw(line);
2d d
(li )
Second line drawn using object
B i St k with
BasicStroke
ith width
idth 10
g2d.setStroke(new BasicStroke(10));
line = new Line2D.Double(10, 30, 100, 30);
g2d draw(line);
g2d.draw(line);
www.ahlashkari.com
27
Rectangle
Class Rectangle2D is used for drawing a
rectangle. It has 2 inner classes :
Rectangle2D.Float and Rectangle2D.Double.
To create object Rectangle2D, use :
new Rectangle2D.Float(x,
R t
l 2D Fl t( y, width,
idth h
height)
i ht)
OR
new Rectangle2D.Double(x,
Rectangle2D Double(x y
y, width
width, height)
www.ahlashkari.com
28
Rectangle
The following messages are understood by
object Rectangle2D:
setRect(float x, float y, float w, float h)
setRect(double x, double y, double w, double h)
To set the top left corner (x, y) and width and
height of the rectangle to w and h.
www.ahlashkari.com
29
Rectangle
(x, y)
width
height
www.ahlashkari.com
30
Example..
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
java awt geom *;
public class Rectangle1 extends JApplet {
private static int SIZE = 30;
private static int DISTANCE = 5;
private
i t static
t ti int
i t X_INIT
X INIT = 20;
20
private static int Y_ROW = 10;
private static int NUMRECT = 10;
Draw rectangle
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
int x = X_INIT;
Rectangle2D Double rect = new Rectangle2D.Double();
Rectangle2D.Double
Rectangle2D Double();
for (int i=1; i <= NUMRECT; i++) {
rect.setRect(x, Y_ROW, SIZE, SIZE);
Increase distance
g2d.draw(rect);
in x direction
x += (SIZE+DISTANCE);
}}}
www.ahlashkari.com
31
Output:
www.ahlashkari.com
32
Exercise
Given the following shapes:
20
60
100
140
20
60
100
Write a java program to draw these shapes
Find out how to use RoundRect to draw
rectangle with rounded corners
www.ahlashkari.com
33
Ellipse
(x, y)
height
width
www.ahlashkari.com
34
Ellipse
Used to draw circles with
height = width
To create object ellipse:
new Ellipse2D.Float(x, y, width, height)
OR
new Ellipse2D.Double(x, y, width, height)
www.ahlashkari.com
35
Ellipse
The following messages are understood by
object Ellipse2D:
setFrame(float x,
x float y
y, float w,
w float h)
setFrame(double x, double y, double w,
double h))
To set the top left corner, width and height as
(x, y), w and h.
www.ahlashkari.com
36
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
public
p
blic class Ellipse e
extends
tends JApplet {
private static int SIZE = 50;
private static int DISTANCE = 10;
Increase
private static int X_INIT = 20;
private static int Y_ROW
Y ROW = 10;
thickness
private static int NUMELLIPSE = 5;
D
Draw
ellipse
lli
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
i t x = X_INIT;
int
X INIT
Ellipse2D.Double elips = new Ellipse2D.Double();
for (int i=1; i <= NUMELLIPSE; i++) {
elips.setFrame(x, Y_ROW, SIZE, SIZE);
g2d setColor(Color red);
g2d.setColor(Color.red);
g2d.setStroke(new BasicStroke(i));
Increase distance
g2d.draw(elips);
x += (SIZE-DISTANCE);
} } }
www.ahlashkari.com
37
Output:
www.ahlashkari.com
38
Exercise
Given the following shapes:
20
60
80
140
20
60
100
Write a java program to draw these shapes
www.ahlashkari.com
39
Arc
Arcs can be represented by Arc2D object
( x, y)
a rc
a n g le
s ta r tin g
a n g le
h e ig h t
w id th
www.ahlashkari.com
40
Arc
To create an arc object:
new Arc2D.Float(x, y, width, height, startingAngle,
arcAngle, type)
OR
new Arc2D.Double(x,
A 2D D bl ( y, width,
idth h
height,
i ht
startingAngle, arcAngle, type)
Type can be specified as Arc2D.OPEN, Arc2D.PIE or
Arc2D.CHORD
www.ahlashkari.com
41
Arc type
Arc2
Arc
2D.OPEN
Arc2
Arc
2D.PIE
www.ahlashkari.com
Arc2
Arc
2D.CHORD
42
import java.awt.
java.awt.*;;
import javax.swing.*;
import java.awt.geom.*;
public class ArcDemoP_01 extends JApplet {
private static int X_TT_HEAD
X TT HEAD = 100;
private static int Y_TT_HEAD= 100;
private static int X_TT_EYE = 100;
private static int Y_TT_EYE = 80;
private static int RADIUS_HEAD = 50;
private static int RADIUS_EYE
RADIUS EYE = 5;
private static int STARTANGLE= 30;
www.ahlashkari.com
43
public void paint(Graphics g) {
G
Graphics2D
hi 2D g2d
2d = (Graphics2D)
(G
hi 2D) g;
Arc2D head = new Arc2D.Double(
X TT HEAD - RADIUS_HEAD,
X_TT_HEAD
RADIUS HEAD,
Y_TT_HEAD - RADIUS_HEAD,
2*RADIUS_HEAD, 2*RADIUS_HEAD, STARTANGLE,
360-2*STARTANGLE, Arc2D.PIE);
g2d.setPaint(Color.magenta);
g2d fill(head);
g2d.fill(head);
Ellipse2D eye = new Ellipse2D.Double(
X_TT_EYE - RADIUS_EYE, Y_TT_EYE - RADIUS_EYE,
2*RADIUS_EYE, 2*RADIUS_EYE);
g2d setPaint(Color white);
g2d.setPaint(Color.white);
g2d.fill(eye); }
}
www.ahlashkari.com
44
Output
www.ahlashkari.com
45
Polygon and PolyLine
Polygon
P
l
: shape
h
which
hi h iis contsructed
t
t db
by severall
connected line segments to form a closed space
Polygaris : shape which is constructed by several
connected line segments, however the last vertex is
not connected to the first vertex
GeneralPath object is used to represent a polygon
or polyline.
To create object GeneralPath
new GeneralPath()
www.ahlashkari.com
46
Polygon and PolyLine
Methods of object GeneralPath:
moveTo(x, y) :add vertex (x, y)
li T ( y):
lineTo(x,
) add
dd vertex
t (x,
( y)) which
hi h is
i
connected to current vertex
closePath():
c
ose a (): c
close
ose the
e space c
created
ea ed
Method closePath() is called if object
GeneralPath is used to p
present a p
polygon
yg
www.ahlashkari.com
47
Array x[] and y[]
store x and y values
for polygon
public
bli class
l
Polygon
P l
extends
t d JApplet
JA l t {
public void paint(Graphics g) {
Return to
Starting
g position
pint[] x = {90, 85, 140, 185, 200, 200, 185, 140, 85};
int[] y = {90, 85, 30, 75, 60, 120, 105, 150, 95};
(90,90)
Graphics2D g2d = (Graphics2D) g;
Go to position
(90,90)
GeneralPath poly = new GeneralPath();
poly.moveTo(x[0], y[0]);
for (int i=1;
i 1; i < x.length;
x length; i++)
Draw polygon using
poly.lineTo(x[i], y[i]);
poly.closePath();
x[] and y[] coordinates
g2d.draw(poly);
}
48
www.ahlashkari.com
}
Output:
Starting coordinate
(90,90)
www.ahlashkari.com
49
Example
Click Ellipse button
www.ahlashkari.com
50
Example
www.ahlashkari.com
51
import java.awt.*;
import javax.swing.*;
import java.awt.geom.
java awt geom *;;
import java.awt.event.*;
public class DrawShape extends JApplet implements ActionListener{
private int x,y;
x y;
private String s="";
private int height,width,radius;
GraphicDisplay graphic = new GraphicDisplay();
public void init(){
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
JP
JPanel
l panell = new JPanel();
JP
l()
JButton line = new JButton("Line");
line.addActionListener(this);
panel.add(line);
JButton circle = new JButton("Ellipse");
circle.addActionListener(this);
panel.add(circle);
pane.add(panel,"North");
pane.add(graphic, "Center");
}
www.ahlashkari.com
Preparing
container
Register
components
GraphicDisplay class
52
public void actionPerformed(ActionEvent e){
s = e.getActionCommand();
e getActionCommand();
if(s.equals("Line")) {
String inputDatax =
JOptionPane.showInputDialog(null,"x coordinate");
x = Integer.parseInt(inputDatax);
String inputDatay = JOptionPane.showInputDialog(null,"y
);
coordinate");
If button “Line” is
clicked, get the starting
and end point for line
y = Integer.parseInt(inputDatay);
String inputx1 =
JOptionPane showInputDialog(null "height
JOptionPane.showInputDialog(null,
height ");
);
int x1 = Integer.parseInt(inputx1);
String
g inputy1
p y =
JOptionPane.showInputDialog(null,"width ");
int y1 = Integer.parseInt(inputy1);
graphic.setShape(x, y, x1, y1, s);
}
www.ahlashkari.com
53
If button “Ellipse” is
else
clicked, get
{
((x,y,height
,y, g and width))
String inputDatax = JOptionPane.showInputDialog(null,"x for ellipse
coordinate");
x = Integer.parseInt(inputDatax);
String inputDatay = JOptionPane.showInputDialog(null,"y
coordinate");
y = Integer.parseInt(inputDatay);
Integer parseInt(inputDatay);
String inputheight = JOptionPane.showInputDialog(null,"height ");
g = Integer.parseInt(inputheight);
g p
( p
g );
height
String inputwidth = JOptionPane.showInputDialog(null,"width ");
width = Integer.parseInt(inputwidth);
graphic.setShape(x, y, height, width, s);
}
}
}
www.ahlashkari.com
54
class GraphicDisplay extends JPanel {
private int height,width,radius;
private int x,y;
private String s = "";
This class will display the
Shape chosen through
button
public void setShape(int xx, int yy, int l, int t, String shape) {
x = xx;
y = yy;
width = l;
height = t;
s = shape;
repaint();
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
Ellipse2D.Double elips = new Ellipse2D.Double();
if (s.equals("Line"))
(
l ("Li ")) {
g2d.draw(new Line2D.Double(x, y, x+width, y+height));
}
else{
g2d.draw(new Ellipse2D.Double(x, y, width, height));
}
}}
www.ahlashkari.com
return
55
Questions
www.ahlashkari.com
56
THANK YOU
Arash Habibi Lashkari
PHD. Candidate of UTM
Kuala Lumpur,
Lumpur Malaysia
Feb, 2010
THE END
www.ahlashkari.com
57