Title: Java Graphics
1- Java Graphics
- Objectives
- To understand Graphics contexts and objects
- To be able to manipulate colours and fonts
- To be able to understand and use the Graphics
methods
2The Co-ordinate System
(0,0)
X axis
(x,y)
Y axis
3Graphics Contexts and Graphics Objects A Java
Graphics Context enables drawing on the
screen. A Graphics object manages a context by
controlling how information is
drawn. Consider the following method found in
Applets public void paint(Graphics g) g
represents a reference to the Graphics object
managing the applets graphics context. The
paint methods is not often used directly by the
programmer.
4Should a programmer need to force paint, a call
to the repaint method may be made. repaint()
This makes a call to the components update
method which will call paint directly Colour
Control Colours are defined and manipulated in
Java through class Color. Constant colour values
are defined in this class. New colours may
be defined using RGB values Color c new
Color(128, 128, 128) // Gray
5Displaying Colours in an Applet import
java.awt. import javax.swing. public class
ShowColours extends JApplet public void
paint(Graphics g) // set new colour using
integers g.setColor( new Color(255, 0 , 0)
) g.fillRect(25, 25, 100, 20)
g.drawString( "Current RGB "g.getColor(),
130, 40) // set new drawing color
using static colour objects
g.setColor(Color.blue) g.fillRect(25, 50,
100, 20) g.drawString( "Current RGB
"g.getColor(), 130, 65)
6Font Control import javax.swing. import
java.awt. public class FontTest extends
JApplet public void paint(Graphics g) //
set font to Serif (Times), bold, 12pt
g.setFont( new Font("Serif", Font.BOLD, 12) )
g.drawString( "Serif 12 point bold.", 20, 50)
// set font to monspaced (courier),
italic, 24pt g.setFont( new
Font("Monospaced",Font.ITALIC,24))
g.drawString( "Monospaced 24 point
italic.",20,70) // set font to Serif,
bolditalic, 24pt g.setFont( new
Font("Serif", Font.BOLDFont.ITALIC,
24) ) g.drawString( "Serif
24 point bold and italic.", 20, 90)
7Font Metrics Class FontMetrics defines methods
which provide measurement information about a
font. Font f FontMetrics fm
f.getFontMetrics() int a fm.getAscent()
int d fm.getDescent() int h
fm.getHeight()
leading
Xy1Ô
height
ascent
descent
8Lines, Rectangles and Ovals public void
drawLine(int x1, int y1, int x2, int
y2) g.drawLine(10,10,20,20) public void
drawRect(int x, int y, int width, int
height) g.drawRect(10,10,20,20) public void
fillRect(int x, int y, int width, int
height) g.fillRect(10,10,20,20) public void
drawRoundRect(int x, int y, int w, int h, int
aw, int ah) g.drawRoundRect(10,10,20,20,5,5)
9import javax.swing. import java.awt. public
class GraphicsTest extends JApplet public void
paint(Graphics g) g.drawLine(10,10,20,20)
g.drawRect(10,40,20,20)
g.fillRect(10,70,20,20)
g.drawRoundRect(10,100,20,20,5,5)
g.drawRoundRect(10,130,100,100,20,20)
g.drawOval(10,210,20,20)
g.fillOval(10,240,20,20)
10(No Transcript)