References:
'Java Certification Guide' Heller.Roberts,
'Just Java' P.van der Linden,
The JDK 1.2.2 api documentation
Every visual programming environment needs a way to'paint to the monitor
screen,
either by creating library visual components or doing custom graphic
rendering. A
visual component for instance will typically include a border which
is represented by
a rectangle drawn with some border dressing. Inside the border a title
will be drawn.
More elaborate control presentations may include icons, small images
that are added
accent the appearance of the control.
The same collection of method calls that are used by component designers
are available
to the Java developer to either customize the appearance of the supplied
components
or just to draw pictures and create animations either for personal
or commercial use.
Graphics is the name given to the subject area that looks at drawing
and rendering
images.
The Mechanics of Rendering Images
The tasks of drawing the various components in Java is handled for the
most part by the
Graphics class. From the developer's point of view it is just another
class that is described
in the library. It is also called the Graphics Context. This alludes
to the fact that when it
comes to graphics most of the calls reach down and use the tools that
are available on
the native platform. So on a Mac, the java environment is reaching
into the Mac toolkit
and rendering lines and rectangles the same way a developer working
for Apple would
make the calls. The same would be true for the Windows platform. Another
thing that
makes you realize the Graphics class is a little different is you never
instantiate it. You
get a handle to Graphics class supplied to you in the paint method
or can get a graphics
object from a method call. We look at the Graphics class in more detail
later in the note.
The GUI or Event Thread
The Java Environment is multithreaded. This means it can coordinate
several processes
happening at the same time all. The Java Virtual Machine launches one
thread to run the
users program. It also launches a a background thread called the garbage
collector to
takes care freeing memory that has be allocated but is no longer in
use. Another important
thread that is started each time the runtime environment is invoked
is the GUI thread.
The GUI thread is also referred to as the Event Thread or the AWT thread.
It derives
these names from it's dual role of painting visual objects to screen
and also processing
the events that may be generated in conjunction with the use of these
visual controls.
The thread accomplishes it's painting tasks by executing a series of
method calls on
component objects at regularly timed intervals and also when ever the
need arises.
Examples of when a call to repaint would be made is if a container
was resized or
one visual panel covers another panel. The programmer can introduce
his or her
own graphical elements by overriding these methods.
repaint, update & paint
The repaint, update and paint methods are all defined in Component,
the top level
visual class which inherits directly from the Object class. All the
visual components
inherit from Component and are painted to screen using these three
methods. They
are called in order, with repaint calling update
and update calling paint. The repaint( )
method schedules calls to update every 100 milliseconds
by default. The update( )
method takes care of clearing a screen essentially
by repainting the entire surface of
the given component with a rectangle that is
set to whatever to the background color.
Once the background is repainted, update calls
paint to render the screen with
whatever imagery is described in the paint method.
This sounds like a lot of painting
and it is but it is just a reflection of the
dynamic way all images are presented on
computer monitors where the screen is refreshed
constantly by the electron guns
firing electrons at the phosphors on the screens
inner surface.
Table summarizing the methods that render java
visual elements to screen
void repaint( ) | repaint( ) is called to put to screen, changes
you have made
to an item's state or appearance. repaint( ) schedules calls to update( ), on most systems, every 100 milliseconds |
void update(Graphics g) | provides a 'port' to participate in window painting
The default
is to clear a component's area to the background color then call paint( ) |
void paint(Graphics g) | paint can be overridden to dynamically change the display |
When we were studying applet, we saw how we could
override the paint function to
control how the component was rendered to screen.
Applet's paint method is the same
paint that we see here which is part of this
general painting mechanism used by all visual
components.
The repaint( ) method is sometimes called explicitly
by a programmer's code when some
change to the appearance of the GUI has been
made, perhaps a change to a title on a label
or a value in a table. The method forces a repaint.
It is handy because it doesn't require
a Graphics context like update and paint and
so is easy to introduce in the GUI code.
The method is defined in several overloaded forms.
The other forms allow restricting the
area that repainting and the maximum amount of
time that transpires before a repaint is
made.
The update method is often overridden to reduce
flicker. We will see this technique a little
later. The basic strategy here is to eliminate
the painting the background. The update method
can also be used to create special effects as
it can collect images if the background is being
repainted.
The definition of update( )
public void update(Graphics g){
g.setColor(getBackground(
));
g.fillRect(
0, 0, width, height);
g.setColor(getForeground(
));
paint(g);
}
The paint( ) method is the workhorse for presenting
graphics. It provides a graphics
context reference that can be used to call the
various drawing methods available in the
Graphics class. Paint's graphics context can
also be cast to the 2DGraphics object
making available the more sophisticated drawing
methods of the 2D class. The paint
method is the right place to put your custom
drawing routines as paint will always be
called appropriately to render the screen.
Color, Font and Graphics Classes
If the Graphics class is the principle actor in
java's visual stage, important supporting
roles are provided by the Color, Font and Image
classes. We look at the Color and
Font class here along with the Graphics class
and defer dealing with images to the
next section.
Color Class
Class Color is in the awt package. Java uses the
RGB model to describe colors where
each tint is composited from their red, green
and blue components. The vividness of
each color can be described using three bytes, one for each color where
0 is darkest
& 255 is brightest. The Color class constructors also allows these
colors to be created
from float values or a single int containing all three color values.
Color class also provides
static fields for each color such as Color.blue
as a convenience when you need a simple
color. The static fields are blue, cyan, darkGray,
gray,
green, lightGray, magenta, orange,
pink, red, white and yellow. The following table
shows the Color class constructors.
Color Class Constructors
Color(float r, float g, float b) | Creates an opaque sRGB color with the specified
red,
green, and blue values in the range (0.0 - 1.0). |
Color
(float r, float g, float b, float a) |
Creates an sRGB color with the specified red, green,
blue, and alpha values in the range (0.0 - 1.0). |
Color(int rgb) | Creates an opaque sRGB color with combined RGB
value consisting of the red component in bits 16-23, the green in bits 8-15, and the blue in bits 0-7. |
Color
(int rgba, boolean hasalpha) |
Creates an sRGB color with the specified combined
RGBA value consisting of the alpha component in bits 24-31, the red component in bits 16-23, the green in bits 8-15, and the blue in bits 0-7. |
Color
(int r, int g, int b) |
Creates an opaque sRGB color with the specified
red,
green, and blue value`s in the range (0 - 255). |
Color(ColorSpace cspace,
float[ ] components, float alpha) |
Creates a color in the color space of the supplied
ColorSpace with the color components specified in the float array and the specified alpha. |
The HSB model
The HSB model uses hue, saturation and brightness
to describe colors and is
not directly supported by java in constructors although methods are
provided
to interchange between the two color systems.
Transparency
An additional alpha component describing a pixels
transparency can be included with
the RGB model. Look at the different Color constructors
below to see how the alpha
value is incorporated into the Color class constructors.
(Pixel
is an abreviation of 'picture
element'. A computer screen may be comprised of a matrix of 1024 x
768 pixels.)
The following example shows how the bits of an int value that are occupied
by the
alpha, red, green and blue.
Example
| alpha bits 31 to 24 | red bits 23 to 16 | green bits 15 to 8 | blue bits 7 to 0 |
An alpha value of 0 is totally transparent while
a value of 255 is a solid color.
Values between are said to vary in translucence
or opacity.
The Majority or Color Class Methods
The following table shows most of the color class
methods. Among others, there
are convenience brighter( ) darker( ) methods
that can be used in rollover effects,
information retrieving methods and methods to
convert to and from the HSB model.
Color brighter( ) | Creates a brighter version of this color. |
Color darker( ) | Creates a darker version of this color. |
static Color
decode(String nm) |
Converts a string to an integer and returns
the specified opaque color. |
boolean equals(Object obj) | Determines whether an object is equal to this color. |
int getAlpha( ) | Returns the alpha component. |
int getBlue( ) | Returns the blue component. |
static Color
getColor(String nm) |
Finds a color in the system properties.
// one of three getColors |
int getGreen( ) | Returns the green component. |
static Color getHSBColor
(float h, float s, float b) |
Creates a Color object based on values supplied
for the HSB color model. |
int getRed( ) | Returns the red component. |
int getRGB( ) | Returns the RGB value representing the color in
the
default sRGB ColorModel. |
float[]
getRGBColorComponents (float[] compArray) |
Returns a float array containing the color components
(no alpha) of the Color, in the default sRGB color space. |
float[] getRGBComponents
(float[] compArray) |
Returns a float array containing the color and
alpha
components of the Color, as represented in the default sRGB color space. |
int getTransparency( ) | Return the transparency mode for this Color. |
int hashCode( ) | Computes the hash code for this color. |
static int HSBtoRGB
(float hue, float saturation, float brightness) |
Converts the components of a color, as specified
by
the HSB model, to an equivalent set of values for the default RGB model. |
static float[]
RGBtoHSB (int r, int g, int b, float[] hsbvals) |
Converts the components of a color, as specified
by
the default RGB model, to an equivalent set of values for hue, saturation, and brightness, the components of the HSB model. |
String toString( ) | Returns a string representation of this color. |
The following code sample is supplied to study color combinations and
is used in the
exercise at the end of the note.
Color Class Code Sample
import java.awt.*;
class Colors extends Frame{
public static void main(String[] args){
Label p=null;
Colors colors=new Colors( );
colors.setLayout(new GridLayout(3,4));
colors.setBackground(Color.white);
String[] colorArray= new String[]
{" blue"," cyan"," darkGray","
gray"," green"," lightGray"," magenta",
" orange"," pink"," red","
white"," yellow"};
int[][] intArray=new int[][]{ new int[]{0,0,255},new int[]{0,255,255},
new int[]{64,64,64},new int[]{128,128,128},
new int[]{0,255,0},new int[]{192,192,192},
new int[]{255,0,255},new int[]{255,160,0},
new int[]{255,170,170}, new int[]{255,0,0},
new int[]{255,255,255},new int[]{255,255,0}
};
for(int i=0;i<12;i++){
p =new Label(colorArray[i]);
p.setBackground(new Color(intArray[i][0],intArray[i][1],intArray[i][2]));
if(colorArray[i].equals(" darkGray"))
p.setForeground(Color.white);
colors.add(p);
}
colors.setSize(400,400);
colors.setVisible(true);
GetColors gc=new GetColors();
}
}
/* A class to get the red green blue values of the base set of colors. */
class GetColors{
GetColors(){
int r,g,b;
r=Color.blue.getRed();
g=Color.blue.getGreen();
b=Color.blue.getBlue();
System.out.println("blue: "+r +" "+ g +" "+ b);
r=Color.cyan.getRed();
g=Color.cyan.getGreen();
b=Color.cyan.getBlue();
System.out.println("cyan: "+r +" "+ g +" "+ b);
r=Color.darkGray.getRed();
g=Color.darkGray.getGreen();
b=Color.darkGray.getBlue();
System.out.println("darkGray: "+r +" "+ g +" "+ b);
r=Color.gray.getRed();
g=Color.gray.getGreen();
b=Color.gray.getBlue();
System.out.println("gray: "+r +" "+ g +" "+ b);
r=Color.green.getRed();
g=Color.green.getGreen();
b=Color.green.getBlue();
System.out.println("green: "+r +" "+ g +" "+ b);
r=Color.lightGray.getRed();
g=Color.lightGray.getGreen();
b=Color.lightGray.getBlue();
System.out.println("lightGray: "+r +" "+ g +" "+ b);
r=Color.magenta.getRed();
g=Color.magenta.getGreen();
b=Color.magenta.getBlue();
System.out.println("magenta: "+r +" "+ g +" "+ b);
r=Color.orange.getRed();
g=Color.orange.getGreen();
b=Color.orange.getBlue();
System.out.println("orange: "+r +" "+ g +" "+ b);
r=Color.pink.getRed();
g=Color.pink.getGreen();
b=Color.pink.getBlue();
System.out.println("pink: "+ r +" "+ g +" "+ b);
r=Color.red.getRed();
g=Color.red.getGreen();
b=Color.red.getBlue();
System.out.println("red: "+ r +" "+ g +" "+ b);
r=Color.white.getRed();
g=Color.white.getGreen();
b=Color.white.getBlue();
System.out.println("white: "+ r +" "+ g +" "+ b);
r=Color.yellow.getRed();
g=Color.yellow.getGreen();
b=Color.yellow.getBlue();
System.out.println("yellow: "+ r +" "+ g +" "+ b);
}
}
Fonts and FontMetrics
Following the Color class the Font and FontMetrics
class play important supporting
roles to the Graphics class in rendering graphics
in a java program. Fonts are used to
draw text in the abstract windowing toolkit. Fonts are encapsulated
in Java in the font
class.The most common Font constructor is.
public Font( String name, int style, int size)
Example
JLabel label = new JLabel( );
Font font = new Font ("SansSerif ", Font.ITALIC, 24 );
label.setFont( font );
// The font constructor takes
the name of a Font, a value indicating whether it is italic, plain or
// bold (or a combination of
these), and the size of the font in pixels
Generally available java fonts are 1) TimesRoman
2) Courier 3) Helvetica 4) Symbol
5) Dialog The older jdk's called TimesRoman Serif,
Helvetica SansSerif and Courier
Monospaced. Calling the now deprecated getFontList(
) on the systems toolkit will
tell you what fonts are available. Though you
will get a deprecation report from the
javac compiler the call still works.
Example String fontnames[] = Toolkit.getDefaultToolkit( ).getFontList( );
Following is a code sample that uses this call. It returns a short list
of fonts that
the java environment maintains. The code sample is followed by the
list it outputs
on a system running the jdk version 1.3.1.
Code using deprecated getDefaultToolkit( )
public class FontT{
public static void main(String[] args){
String fontnames[] = java.awt.Toolkit.getDefaultToolkit(
).getFontList( );
for(int i=0;i<fontnames.length;i++)
System.out.println(fontnames[i]);
}
}
C:\NewCode>java FontT
Dialog
SansSerif
Serif
Monospaced
DialogInput
Following is the suggested replacement code for
the deprecated method shown
above. Using this code derived
the following
extensive list of fonts, returned from
the same system used in the example above running jdk1.3.1. In order
to capture
the output which exceeded a screen the output of the java statement
was redirected
to file with the line below.
Example
C:\> java AvailableFonts > FontFile
GraphicsEnvironment Code Sample
import java.awt.*;
class AvailableFonts{
public static void main( String args[ ] ){
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment(
);
String [ ] f= ge.getAvailableFontFamilyNames( );
for(int i=0;i<f.length;i++)
System.out.println( f[i] );
}
}
Output // the original output showed a font per line without commas
Arial, Arial Black, Arioso, Bedrock, Chevara,
ChevaraOutline, Comic Sans MS, CommonBullets,
Conga
Courier New, Dauphin, Default, Dialog, DialogInput,
Helmet, HelmetCondensed, Impact, Lucida Bright,
Lucida Console, Lucida Sans, Lucida Sans
Typewriter,
Marlett, Monospaced, SansSerif, Serif, SPW,
StarBats,
StarMath, Symbol, Tahoma, Times New Roman,
Timmons,
Verdana, Webdings, Wingdings
Font class
Font class has increased dramatically in size
going from jdk 1.1 to 1.2. It
has expanded from 14 to 52 methods. This is largely
due to java 2D classes
adding features allowing the customizing of
fonts. Looking at the fields in
the next table alludes to the international character
of the Unicode character
set where some sets will use a centered or hanging
baseline rather than the
the Roman baseline where characters stand on
top of the baseline.
Font Class Fields
static int BOLD | The bold style constant. |
static int CENTER_BASELINE | The baseline used in ideographic scripts like Chinese,
Japanese, and Korean when laying out text |
static int HANGING_BASELINE | The baseline used in Devanigiri and similar scripts
when
laying out text static int ITALIC The italicized style constant. |
protected String name | The logical name of this Font, as passed to the constructor. |
static int PLAIN | The plain style constant. |
protected float pointSize | The point size of this Font in float. |
static int ROMAN_BASELINE | The baseline used in most Roman scripts when laying out text |
protected int size | The point size of this Font, rounded to integer. |
protected int style | The style of this Font, as passed to the constructor. |
Constructors
There are only two Font class constructors. The less common of the two
takes a
Map object containing the specified attributes. The actual object passed
in is an
object of Attribute class that implements the Map interface. The Attributes
class
is found in the java.util.jar package.
Font(Map attributes) | Creates a new Font with the specified attributes. |
Font(String name, int style, int size) | Creates a new Font from the specified name, style
and point size. |
Font Methods
(26 of 52 nethods)
boolean canDisplay(char c) | Checks if this Font has a glyph for the specified character. |
int canDisplayUpTo(char[]
text, int start, int limit) |
Indicates whether this Font can display the characters
in the specified text starting at start and ending at limit. |
int canDisplayUpTo
(String str) |
Indicates whether or not this Font can display
a
specified String. |
static Font
decode(String str) |
Returns the Font that the str argument describes. |
Font deriveFont(float size) | Creates a new Font object by replicating the current
Font
object and applying a new size to it. // one of five |
boolean equals(Object obj) | Compares this Font object to the specified Object. |
protected void finalize( ) | Disposes the native Font object |
Map getAttributes( ) | Returns a map of font attributes available in this Font |
byte getBaselineFor
(char c) |
Returns the baseline appropriate for displaying
this
character. |
String getFamily( ) | Returns the family name of this Font. //one of two |
static Font
getFont(String nm) |
Returns a Font object from the system properties
list.
//one of three |
String getFontName( ) | Returns the font face name of this Font. // one of two |
float getItalicAngle( ) | Returns the italic angle of this Font |
Rectangle2D
getMaxCharBounds (FontRenderContext frc) |
Returns the bounds for the character with the maximum
bounds as defined in the specified FontRenderContext |
String getName( ) | Returns the logical name of this Font. |
int getNumGlyphs( ) | Returns the number of glyphs in this Font. |
int getSize( ) | Returns the point size of this Font, rounded to an integer. |
float getSize2D( ) | Returns the point size of this Font in float value |
int getStyle( ) | Returns the style of this Font. |
AffineTransform
getTransform( ) |
Returns a copy of the transform associated with this Font. |
int hashCode( ) | Returns a hashcode for this Font. |
boolean
hasUniformLineMetrics( ) |
Checks whether or not this Font has uniform line metrics. |
boolean isBold( ) | Indicates whether or not this Font object's style is BOLD |
boolean isItalic( ) | Indicates whether or not this Font object's style is ITALIC. |
boolean isPlain( ) | Indicates whether or not this Font object's style is PLAIN. |
String toString( ) | Converts this Font object to a String representation. |
FontMetrics
FontMetrics class returns exact pixel measurements of the dimensions
and positions of
text. getLeading( ) returns the number of pixels
between the maximum descent of one
line and the maximum ascent of the next line
getAscent( ) returns in pixels the distance
from the baseline to the top of most of the characters
in a font getMaxAscent( ) returns
in pixels the distance from the baseline to the top of the tallest
character in a font. These
methods all make better sense after considering the meaings of the
value types these
methods return.
// getMaxAscent may return the
same value as getAscent( )
FontMetric class provides get methods for each
of the following character measurements;
Diagram Showing The Different Aspects Used to Descibe Font Metrics
__
__ ^ MaxAscent is
the height of the highest letter in the font set as measured from the baseline
^ Ascent
is
the distance of the average character as measured from the baseline to
the character top
__ v Baseline
the base where the average character rests
__ v Descent
is the average extension of characters that extend below the baseline like
the letter ' y '
__ v MaxDescent the
greatest depth below the baseline reached by any character of the font
set
_^_ Leading
is
the
inter-line gap from theMaxDescent
of
one line to the MaxAscent of the line
below
v
__
__ ^ MaxAscent //
next line below
^ Ascent
__ v Baseline//
" " "
__ v Descent
__ v MaxDescent //
" " "
FontMetrics class
Fields
protected Font font | The actual Font from which the font metrics are created. |
Constructor
protected FontMetrics
(Font font) |
Creates a new FontMetrics object for finding height
and width info
about the specified Font and specific character glyphs in that Font. |
FontMetric Methods
(15 of 26 methods)
int bytesWidth
(byte[] data, int off, int len) |
Returns the total advance width to show the
specified array of bytes in this Font. |
int charWidth(char ch) | Returns the advance width of the specified
character in this Font. // 1 of 3 |
int getAscent( ) | Returns the font ascent of the Font described
by this FontMetrics object. |
int getDescent( ) | Returns the font descent of the Font described
by this FontMetrics object. |
Font getFont( ) | Gets the Font described by this FontMetrics object. |
int getHeight( ) | Gets the standard height of a line of text in this font. |
int getLeading( ) | Returns the std. leading of the Font described
by this FontMetrics object. |
int getMaxAdvance( ) | Gets the max. advance width of any character
in this Font. |
int getMaxAscent( ) | Returns the max. ascent of the Font described by
this FontMetrics object. |
Rectangle2D
getMaxCharBounds (Graphics context) |
Returns the bounds for the character with max.
bounds in Graphics context. |
int getMaxDescent( ) | Returns the max. descent of the Font described
by this FontMetrics object. |
int[] getWidths( ) | Gets the advance widths of the first 256
characters in the Font. |
boolean
hasUniformLineMetrics ( ) |
Checks to see if the Font has uniform line metrics. |
int stringWidth
(String str) |
Returns the total advance width for showing the
specified String in this Font. |
String toString( ) | Returns a representation of this FontMetrics
object's values as a String. |
The Graphics Class
The Graphics class is abstract and largely comprised of abstract drawing
methods.
The platform-specific version of the Graphics class is called the graphics
context.
It is comprised of a set of native calls to the underlying system's
drawing routines,
expressed in the implementation of the abstract methods of the Graphics
class.
From an applied point of view, you can think of the Graphics class
as a regular
Java class you call drawing methods on. The only difference is you
will never call
a Graphics class constructor. The graphics context is most commonly
seen as the
argument type to the paint( ) method but you can get a graphics context
for any
component or image via a call to getGraphics(
).
For instance,
Example Graphics g = Pic.getGraphics( ); // where Pic may be a Panel, Image or Canvas
The getGraphics( ) method is found in several
classes including Component,
PrintJob, Image, BufferedImage, JComponent, and
View
The dispose( ) should be used to release graphics objects when a graphic
context is
created outside of the paint( ) method. This frees up system resources
and memory
that may be tied up in creating a graphics context.
2D Graphics
The Java 2D API gives provides a new toolkit of drawing methods that allow greater flexibilty in the types of graphics that can be performed. The Java Tutorial at the Sun site provides an good introduction to the 2D API, by D. Adair, J. Ball & M. Pawlan. To view go to http://web2.java.sun.com/docs/books/tutorial/2d/index.html |
Using the 2D class begins with casting the graphics object to it's 2D sibling public void Paint (Graphics g) {
|
Some of Graphics Class' Drawing Methods
Graphics drawing methods are mostly of the form drawXXX(
) or fillXXX( )where
the former outlines and latter fills with a color. A graphics object
has a setColor( )
method to effect the foreground color. The background color relies
on the underlying
component. The default foreground color is black. A fillXXX( ) method
can be used
to effect a change in the general background color. Most textbooks
do a tour of the
common drawing methods so we will do the same. Though they are elemental,
with
a little work they can be used to do sophisticated graphical rendering.
drawString( )
public void drawString(String str, int x, int y)
drawString( ) fills the role for graphics that System.out.print(
) does for the command
console's standard output. x
and y locate
the beginning of the baseline where the string
will be drawn. For this reason setting the baseline's y coordinate
to 0 may put letters
completely off the screen. We can create simple
examples for these methods as we
go and then collect them into a single sample
program.
Example
g.drawString("A few graphics methods",30,20);
drawBytes( ) & drawChars( )
public void drawBytes( byte data[], int offset,
int length, int x int y )
public void drawChars( char data[], int offset,
int length, int x int y )
These methods places length bytes or characters
from offset within data[] to the
point located by (x , y).
Example g.drawChars(characters, 2, 3, 10, 240);
// takes array characters, at
offset 2, for length 3 and at x, y coordinates 10 & 240
drawLine( )
public void drawLine( int x1, int y1, int x2, int y2 );
drawLine( ) connect two points with a line drawn from
the point described
by x1, y1 to the point at x2, y2. The line
is limited to a one pixel width. To
workaround this constraint the fillPolygon( )
can be used in it's place to draw
a thicker line or methods found in the Graphics2D
package can be used.
Example g.drawLine(30,22,160,22);
draw & fillRect( )
public void drawRect( int x, int y, int width,
int height );
public void fillRect( int x, int y, int width,
int height );
These methods can be used to outline or fill a
rectangle. The top left corner of
the rectangle is located at x,y. The width
and height are then specified. The unit
used is pixels. A majority of the graphics methods
build on the approach that
draw and fillRect( ) take, where the upper left
corner is specified along with
the width and height.
Example
g.drawRect(30,30,240,140);
draw & fill3DRect( )
public void draw3DRect( int x, int y, int width,
int height, boolean raised );
public void fill3DRect( int x, int y, int width,
int height, boolean raised );
These methods provide a convenient way of drawing or filling a
3D rectangle
(similar in appearance to a button) If
the boolean values raised is true, the
shading makes the rectangle appear to be elevated
, if false, the rectangle
appears depressed.
Example
g.draw3DRect(250,200,20,30,true);
draw & fillRoundRect( )
public void drawRoundRect( int x, int y, int width,
int height, int arcWidth int arcHeight);
public void fillRoundRect( int x, int y, int
width, int height, int arcWidth int arcHeight);
These are methods that draw or fill rectangles with rounded corners.
arcWidth
and
arcHeight parameters control diameter of rounded
corners in pixels. You can think
of arc width and height as the dimension of a
rectangle that controls the shape of a
controlled oval. This oval then is pressed into
the corners of the rounded rectangle.
Example
g.drawRoundRect(120,50,90,90,80,20);
draw & fillOval( )
public void drawOval( int x, int y, int width,
int height );
public void fillOval( int x, int y, int width,
int height );
The draw and fillOval( ) methods draw an oval inside the imaginary rectangle
described
by the width & height parameters provided
to the method. The imaginary rectangle has
it's top, left corner at the x,y coordinate.
Example
g.drawOval(40,50,80,20);
draw & fillArc( )
public void drawArc(int x, int y, int width,
int height, int startAngle, int arcAngle);
public void fillArc(int x, int y, int
width, int height, int startAngle, int arcAngle);
The draw and fillArc( ) methods continue working with an oval drawn
inside an
imaginary rectangle adding a start angle and an angle of sweep. Only
the part of
the arc that is traced from the start angle to the end of the sweep
angle is drawn
to screen. A positive sweep value causes a counter clockwise
rotation of the arc.
draw & fillPolygon( )
public void drawPolygon(int xPoints[], int yPoints[],
int nPoints);
public void fillPolygon(int xPoints[], int yPoints[],
int nPoints);
A polygon is a closed figure with an arbitrary
number of straight sides. The draw &
fillPolygon( ) methods take two array of points, one for x and one
for y values, along
with a int value to specify how many points of the polygon should be
drawn. Specifying
different numbers of points will draw different
polygons. Specifying more points than
are defined in the point arrays results in an
ArrayIndexOutOfBounds exception.
Because a polygon is a closed figure by definition,
the first point does not need to be
repeated.
public void drawPolyline(int xPoints[],int yPoints[], int nPoints )
drawPolyline( ) is like drawPolygon
except that it is open. To close
a figure with
drawPolyline( ), the first and last points must be the same. There
is no fillPolyline( )
as this results in the same effect that is achieved by fillPolygon(
)
Graphics Code Sample
The following code sample shows many of these methods in use. The applet
focuses especially on the how arc width and height values are used
to create
the rounded corners using drawRoundRect( ). Note how the corners have
the
shapes corresponding to ovals that would be created if these values
are used.
import java.applet.*;
import java.awt.*;
// <applet code="Drawing.java" width="310" height="280"></applet>
public class Drawing extends Applet{
char[] characters;
int[] X,Y;
public void init (){
characters=new char[]{'A',' ','B','
','C',' ','D' };
X=new int[]{20,40,220,250};
Y=new int[]{210,275,220,270};
setBackground(new Color(0,0,0));
setForeground(new Color(255,255,255));
}
public void paint(Graphics g){
g.drawString("A few graphics methods",30,20);
g.drawChars(characters,2,3,55,240);
//draws B, space and C
g.drawLine(30,22,160,22);
g.drawRect(30,30,240,140);
g.draw3DRect(250,200,20,30,true);
g.setColor(Color.pink);
g.drawOval(40,50,80,20);
g.drawOval(70,80,30,70);
g.setColor(new Color(233,255,233));
g.drawRoundRect(120,50,90,90,80,20);
//same as first oval
g.drawRoundRect(160,70,90,90,30,70);
//same as second oval
g.setColor(Color.yellow);
g.drawString("Note how the oval size
correspond to",30,190);
g.drawString("the rounded corners
of the rectangles",30,210);
g.setColor(Color.green);
g.drawArc(40,210,50,50,140,175);
g.setColor(Color.gray);
g.fillArc(190,230,20,20,45,270);
g.setColor(Color.gray);
g.drawPolygon(X,Y,4);
}
}
a) AWT and GUI are different names for the same background thread.
b) The Event thread is separate from the GUI thread and just deals
with
event handling.
c) Java uses the graphics toolkit of each platform the java virtual
machine
is running on to render graphics.
d) The Graphics context is abstract and therefore cannot be instantiated.
2) Which of the following statements is not correct?
a) The GUI thread is also called the Event thread.
b) the methods to render component are all defined in the Container
class
c) The GUI thread is responsible for painting and handling events
d) The GUI thread is a background thread like the garbage collector
thread.
( b ) // Comment: the painting methods are defined in Component class
3) Which of the following statements is not correct?
a) A Color can be specified using the dot operator as in Color.darkGray
b) An alpha value of 0 is totally transparent
while a value of 255 is a solid color
c) Java supplies constructors to build colors on both the RGB
and HSB models.
d) HSB stands for hue saturation and brightness.
( c )
// Comment: Java has no constructors that receive
colors specified in HSB but
// does supply methods to convert between HSB
and RGB
4) Which of the following may be located on, over
or under the locations where
characters are drawn.
a) MaxDescent
b) Leading
c) BaseLine
d) Ascent
( c )
//Comment: The baseline may be over under or centered characters locations.
5) Which of the following would draw a right angle triangle?
int[] x=new int[]{ 50, 50, 100, 100 }
int[] y=new int[]{ 50,100,100, 50 }
a) drawPolyline(x,y,3);
b) drawPolygon(x,y,3);
c) drawPolyline(x,y,4);
d) drawPolygon(x,y,4);
( b )
6) Select the correct answer. drawOval(150,200, 100, 200); will create an oval
a) whose center is located at the x,y coordinate
(150,200) with a horizontal diameter
of 100 pixels and vertical diameter
of 200 pixels
b) bounded by an imaginary rectangle whose center
is located at the x,y coordinate
(150,200) and whose height
is 100pixels and width is 200 pixels
c) bounded by an imaginary rectangle whose upper
left corner is located at x,y
coordinates (150,200) and
whose height is 100 pixels and whose width is 200 pixels
d) bounded by an imaginary rectangle whose upper
left corner is located at x,y
coordinates (150,200) and
whose height is 200 pixels and whose width is 100 pixels
( d )
1) Pick the incorrect statement.
a) A handle to the graphics context can be obtained when overriding
the
paint method argument.
b) The graphics class makes many calls on native platform resources.
c) a graphics class object can be obtained using getGraphics( )
d) a graphics class object can be created using the Graphic's class
constructor
( d )
2) Which of the following statements is not correct?
a) The Event thread makes the appropriate calls whenever a component
needs to be repainted and also at regularly scheduled
intervals.
b) painting is scheduled to occur by default every 100 milliseconds
c) update( ) calls repaint( ) which calls paint( )
d ) Unlike update( ) and paint( ), repaint( ) does not take a graphics
context
as an argument.
( c )
3) Which of the following statements is not correct?
a) Java's Color class uses a RGB model.
b) There are methods for converting between the HSB model and the RGB
model
c) The most significant byte of a int stores the transparency value.
d) The vividness of each color is described by
a byte (0 is brightest & 255 is darkest).
( d )
4) Which of the following dictates the space between
the MaxDescent of one line
and the MaxAscent of another
line.
a) MaxDescent
b) Leading
c) BaseLine
d) Ascent
( b )
5) Which of the following would draw a closed square?
int[] x=new int[]{ 50, 50, 100, 100 }
int[] y=new int[]{ 50,100,100, 50 }
a) drawPolyline(x,y,3);
b) drawPolygon(x,y,3);
c) drawPolyline(x,y,4);
d) drawPolygon(x,y,4);
( d )
6) To draw a smile on a happy face which of the following will give
the desired effect.
be your best choice. (Assume g is the graphics context.)
a) g.drawArc(50,50,200,100,0,180);
b) g.drawArc(50,50,200,100,0,360);
c) g.drawArc(50,50,200,100,180,180);
d) g.drawArc(50,50,200,100,180,360);
( c )
1.(i) Find out what fonts your computer has by calling the static getDefaultToolkit(
)
on the Toolkit class. (Remember it returns a String array which you'll
have to print to
screen, say using a for loop set to iterate for the stringArray.length)
When you build
your simple class with a main method as it's first line you'll also
have to import
java.awt.* where Toolkit class resides.
(ii) You'll notice the compiler tells you this method is deprecated.
Run the program
with the -deprecation option to see what the compiler says.
(iii) Repeat the excercise using the code sample from the notes containing
the
GraphicsEnvironment references. What are the differences in the fonts
returned by
the two techniques?
2.
Look at the result of running the Colors program code example. In reference
to the
three integer values returned for each color;
(i) What do the colors red green blue have in common?
(ii) What general formula can you use to describe the r g b numbers
that yield grey.
(iii) If red green and blue are called primary colors, What might we
call secondary
and tertiary colors from the colors set returned by the program.
3. Create arrays of x and y coodinates for five points. Draw a polygon
using this array
specifying 3, 4 and 5 points. What do you observe for each?
4. Using Color, Font and Graphics create an art applets to appear on
a HTML
page for 'The Maple General Store'. Use three different font types
and sizes.