Lect.
#10
Graphics in Java
▪ The Graphics class provides the
framework for all graphics operations
within the AWT.
▪ It plays two different, but related, roles.
▪ First, it is the graphics context: Which is the
information that will affect drawing
The Graphics operations including
Class ▪ the background and foreground colors,
▪ the font,
▪ the location and dimensions of the clipping
rectangle (the region of a component in which
graphics can be drawn).
▪ Second, it provides methods for drawing
simple geometric shapes, text, and
images to the graphics destination.
How to use the Graphics class?
❑ In order to draw, a program requires a valid graphics context
(represented by an instance of the Graphics class).
❑Because the Graphics class is an abstract class, it cannot be
instantiated directly.
❑An instance is typically created by a container, and handed to the
program as an argument to a
component’s update() and paint() methods.
❑These two methods, along with the repaint()method, are discussed
in the next section.
The Graphics Coordinate System
❑ The methods described in the following slides take, as parameters,
values that specify how a shape is to be drawn.
❑ For example, the drawLine( ) method expects four parameters.
The first two parameters specify the location of the beginning of the
line, and the last two parameters specify the location of the end of the
line. The exact values to be passed to the drawLine( ) method are
determined by the coordinate system in effect.
❑ A coordinate system is a method for unambiguously specifying the
location of points in space.
❑ Each location in a plane can be specified by two integers, called the
x and y coordinates. The values of the x and y coordinates are
calculated in terms of the point's respective horizontal and vertical
displacement from the origin.
❑ In the case of the AWT, the origin is always the point in the upper-
left corner of the plane.
The Graphics methods
❑ This Graphics class introduces methods for drawing lines, rectangles, ovals
and arcs, and polygons.
❑ Most of the methods that follow come in pairs.
▪ One method (the drawShape( ) method) draws only the outline of the
specified shape,
▪ the other method (the fillShape( ) method) draws a filled version of the
specified shape.
❑ for example:
▪ drawRect () draws only the outline of rectangle,
▪ While, fillRect() draws a filled version of the rectangle.
drawLine ( ) method
❑ This is the simplest of all graphics methods.
❑ Syntax:
void drawLine(int xBegin, int yBegin, int xEnd, int yEnd)
❑ It draws a straight line, a single pixel wide, between the specified
beginning and ending points.
❑ The line will be drawn in the current foreground color.
drawString ( ) method
❑ One of the simplest ways to show a message within the container.
❑ Syntax:
void drawString(String mess, int xBegin, int yBegin)
❑It draws (writes) a string mess, such that, the baseline of its
leftmost character is at position (xBegin, yBegin) in this graphics
context's coordinate system.
❑ The String will be written in the current foreground color.
drawRect ( ) & fillRect ( ) methods
❑ There are two versions for drawing a rectangle:
❑ Syntax:
void drawRect (int x, int y, int w, int h)
void fillRect (int x, int y, int w, int h)
❑ Each of these methods require, as parameters, the x and y coordinates of
the upper-left corner of the rectangle, and the width and the height of the
rectangle.
❑ Both the width and the height must be positive integers.
❑ The rectangle will be drawn in the current foreground color.
❑ To draw a square, all you want is to call this method with equal values for
both w and h.
drawOval ( ) & fillOval ( ) methods
❑ There are two versions for drawing a rectangle:
❑ Syntax:
void drawOval (int x, int y, int w, int h)
void fillOval (int x, int y, int w, int h)
❑ Each of these methods require, as parameters, the x and y coordinates
and the width and height of the rectangle enclosing the oval.
❑ Both the width and the height must be positive integers.
❑ The shape will be drawn in the current foreground color.
❑ To draw a circle, all you want is to call this method with equal values
for both w and h.
drawArc ( ) & fillArc ( ) methods
❑ There are two versions for drawing a rectangle:
❑ Syntax:
void drawArc (int x, int y, int w, int h, int startAngle, int arcAngle)
void fillArc (int x, int y, int w, int h, int startAngle, int arcAngle)
❑ The arc graphics methods require two additional parameters than that of
oval; a start angle and an arc angle, to specify the beginning of the arc and the
size of the arc in degrees (not radians).
❑ The shape will be drawn in the current foreground color.
drawPolgon ( ) & fillPolgon ( ) methods
❑ Polygons are shapes formed from a sequence of line segments.
❑Syntax:
void drawPolygon(int xPoints[], int yPoints[], int nPoints)
void fillPolygon(int xPoints[], int yPoints[], int nPoints)
❑ Each of the polygon graphics methods require, as parameters, the
coordinates of the endpoints of the line segments that make up the polygon.
❑ These endpoints can be specified as two parallel arrays of integers, one
representing the successive x coordinates and the other representing the
successive y coordinates.
❑ The shape will be drawn in the current foreground color.
Example
import javax.swing.JFrame;
import java.awt.Graphics;
public class HappyFace extends JFrame
{
public void paint (Graphics g)
{
g.drawRect (70, 60, 300, 300);
g.drawOval (100, 50, 200, 200);
g.fillOval (155, 100, 10, 20);
g.fillOval (230, 100, 10, 20);
g.drawArc (150, 160, 100, 50, 180, 180);
}
}
Changing Colors and Fonts
❑ The graphic context maintains attributes such as the current painting color and the
current font for drawing text strings
❑ You can use the methods getColor (), setColor (), getFont () and setFont ()
to get or set the color and font.
❑ Syntax:
// Graphics context's current color.
void setColor(Color c)
Color getColor()
// Graphics context's current font.
void setFont(Font f)
Font getFont()
Class Color
❑ The class java.awt.Color provides 13 standard colors as named-constants.
❑ They are: Color.RED, GREEN, BLUE, MAGENTA, CYAN, YELLOW, BLACK,
WHITE, GRAY, DARK_GRAY, LIGHT_GRAY, ORANGE, and PINK.
❑In JDK 1.1, these constant names were in lowercase, e.g., Color.red.
This violates the Java naming convention for constants. In JDK 1.2, the
uppercase names are added. The lowercase names were not removed for
backward compatibility.
❑You can use the toString() to print the RGB values of these color (e.g.,
System.out.println(Color.RED)):
Class Color Constructor & Methods
❑ You can use the RGB values to construct your own color via constructors:
Color(int r, int g, int b); // between 0 and 255
Color(float r, float g, float b); // between 0.0f and 1.0f
Color(int r, int g, int b, int alpha); // alpha specify transparency/opaque
▪ If the value of alpha = 0 then it indicates totally transparent,
▪ While if its value = 255 (or 1.0 f) then it indicates totally opaque
▪ The default alpha is 255 (or 1.0 f) for totally opaque
❑ Examples:
Color myColor1 = new Color(123, 111, 222);
Color myColor2 = new Color(0.5f, 0.3f, 0.1f);
Color myColor3 = new Color(0.5f, 0.3f, 0.1f, 0.5f); // semi-transparent
Class Color Constructor & Methods (cont.)
❑ To retrieve the individual Color components, you can use
▪ getRed( ), getGreen( ), getBlue( ), getAlpha( ), etc.
❑ To set the background and foreground (text) color of a component/container, you
can invoke setBackground (Color c), setForeground (Color c) . For example:
JLabel label = new JLabel("Test");
label.setBackground(Color.LIGHT_GRAY);
label.setForeground(Color.RED);
❑ To set the color of the Graphics context g (for drawing lines, shapes, and texts), use
setColor(color) for example:
g.setColor(Color.RED);
g.drawLine(10, 20, 30, 40); // in Color.RED
Color myColor = new Color(123, 111, 222);
g.setColor(myColor);
g.drawRect(10, 10, 40, 50); // in myColor
Class Font
❑ The class java.awt.Font represents a specific font face, which can be used for
rendering texts.
❑ You can use the following constructor to construct a Font instance
public Font(String name, int style, int size);
▪ name: Font Family name like:
o "Dialog", "DialogInput", "Monospaced", "Serif", or "SansSerif"
o Physical font found in this GraphicsEnvironment.
o You can also use String constants Font.DIALOG, Font.DIALOG_INPUT,
Font.MONOSPACED, Font.SERIF, Font.SANS_SERIF (JDK 1.6)
▪ style: Font.PLAIN, Font.BOLD, Font.ITALIC or Font.BOLD|Font.ITALIC (Bit-
OR)
▪ size: the point size of the font (in pt) (1 inch has 72 pt).
Class Font Methods
❑ You can use the setFont (Font f) method to set the current font for the Graphics
context g for rendering texts. For example,
g.drawString("In default Font", 10, 20); // in default font
Font myFont1 = new Font(Font.SANS_SERIF, Font.ITALIC, 12);
g.setFont(myFont1);
g.drawString("Using the font set", 10, 50); // in myFont1
Font myFont2 = new Font(Font.MONOSPACED, Font.PLAIN, 12);
Font myFont3 = new Font(Font.SERIF, Font.BOLD | Font.ITALIC, 16); // bold and italics
JButton btn = new JButton("RESET");
btn.setFont(myFont2);
JLabel lbl = new JLabel("Hello");
lbl.setFont(myFont3);
......