Basic Graphics In Java With Examples (Part-2)
In the previous article Basic Graphics In Java With Examples I explained the methods of graphics class available for drawing various types of figures. In this article I will carry forward the graphics class with the methods it provides to work with those figures, methods available for working with fonts, colors etc.
There are two painting or drawing modes for the Graphics class:- paint mode which is the default mode and XOR mode. In paint mode, anything we draw replaces whatever is already on the screen i.e. it overwrites any preexisting contents. If you draw a green circle, you get a green circle, no matter what was underneath.
Here is an example to show how paint mode works:-
The behavior of XOR mode is different. XOR stands for eXclusive-OR. The concept behind XOR mode is that drawing the same object twice returns the screen to its original state. This technique was commonly used for simple animations prior to the development of more sophisticated methods and cheaper hardware. The advantage of XOR mode is that the new object is always guaranteed to be visible no matter what color the object is drawn over. It is possible to have new objects XORed onto the window by using setXORMode( ), as follows:
void setXORMode(Color xorColor):- The setXORMode() method changes the drawing mode to XOR mode.
Here, xorColor specifies the color that will be XORed to the window when an object is drawn. For each pixel, the new color is determined by an exclusive-or of the old pixel color, the painting color, and the xorColor.
For example, if the old pixel is red, the XOR color is blue, and the drawing color is green, the end result would be white. To see why, it is necessary to look at the RGB values of the three colors. Red is (255, 0,0). Blue is (0, 0, 255). Green is (0, 255, 0). The exclusive or of these three values is (255, 255, 255), which is white. Drawing another green pixel with a blue XOR color yields red, the pixel's original color, since (255, 255, 255) ^ (0, 0, 255) ^ (0, 255, 0) yields (255, 0, 0).
Here is an example to demonstrate the above concept:-
public abstract void setPaintMode ():- The setPaintMode() method puts the system into paint mode. When in paint mode, any drawing operation replaces whatever is underneath it. setPaintMode() is called to return to normal painting when finished with XOR mode
The cross hairs are XORed onto the window and are always visible, no matter what the underlying color is.
Java supports color in a portable, device-independent fashion. The Color class has predefined constants (all of type public static final Color) for frequently used colors.
The AWT color system allows you to specify any color you want. It then finds the best match for that color, given the limits of the display hardware currently executing your program or applet. These constants, their RGB values, and their HSB values (hue, saturation, brightness) are as follows:
Comparison of RGB and HSB Colors:-
You can also create your own colors, using one of the color constructors. The most commonly used forms are shown here:
Color(int red, int green, int blue):- This constructor is the most commonly used. This constructors requires 3 integers specifying the red, green, and blue values for the color. These values must be between 0 and 255.
Example: new Color(255, 100, 100); // light red.
Color(int rgbValue):- This constructor takes a single integer that contains the mix of red, green, and blue packed into an integer. It allows to combine all three variables in one parameter, rgb. Bits 16-23 represent the red component, and bits 8-15 represent the green component. Bits 0-7 represent the blue component. Bits 24-31 are ignored.
Example: int newRed = (0xff000000 | (0xc0 << 16) | (0x00 << 8) | 0x00);
Color darkRed = new Color(newRed);
Color(float red, float green, float blue):- This final constructor takes 3 floating point values between 0.0 and 1.0 for each of red, green, and blue. Values outside of this range yield unpredictable results.
Once you have created a color, you can use it to set the foreground and/or
background color by using the setForeground( ) and setBackground( ) methods
public int getRed ():- The getRed() method retrieves the red component of a color independently.
public int getGreen ():- The getGreen() method retrieves the green component of a color independently.
public int getBlue ():- The getBlue() method retrieves the blue component of the color independently.
public int getRGB ():- The getRGB() method returns a packed, RGB representation of a color . It retrieves the current settings for red, green, and blue in one combined value. Bits 16-23 represent the red component. Bits 8-15 represent the green component. Bits 0-7 represent the blue component. Bits 24-31 are the transparency bits.
public Color brighter():- The brighter() method creates a new Color that is somewhat brighter than the current color. This method is useful if you want to highlight something on the screen.Black does not get any brighter.
public Color darker():- The darker() method returns a new Color that is somewhat darker than the current color. This method is useful if you are trying to de-emphasize an object on the screen.
Setting the Current Graphics Color
By default, graphics objects are drawn in the current foreground color.
void setColor(Color newColor)
Here, newColor specifies the new drawing color.
This method is used to change the current foreground color to the newcolor specified in its agument.
You can obtain the current color by calling getColor() method:
Color getColor( )
Following is an examples that illustrates the colors:
The hue-saturation-brightness (HSB) color model is an alternative to red-green-blue (RGB) for specifying particular colors. There are some methods available to represent colors in terms of hue, saturation and brightness.
Hue represents the base color to work with. Figuratively, hue is a wheel of color. It is specified with a number between 0.0 and 1.0 (the colors are approximately: red, orange, yellow, green, blue, indigo, and violet). white is 0; and black is 1.
Saturation represents the color's purity, ranging from completely unsaturated (either white or black depending upon brightness) to totally saturated (just the base color present). It represents light pastels to intense hues.
Brightness is the desired level of luminance, ranging from black (0) to the maximum amount determined by the saturation level. 1 is bright white.
Color supplies two methods that converts between RGB and HSB.
public static int HSBtoRGB (float hue, float saturation, float brightness):- HSBtoRGB( ) returns a packed RGB value compatible with the Color(int) constructor. As with the constructor, bits 16-23 represent the red component, 8-15 represent the green component, and 0-7 represent the blue component. Bits 24-31 are ignored.
public static float RGBtoHSB (int red, int green, int blue, float hsbvalues):-
The RGBtoHSB() method allows to convert a specific red, green, blue value to the hue, saturation, and brightness equivalent. RGBtoHSB() returns the results in two different ways: the parameter hsbvalues and the method's return value. The values of these are the same. If you do not want to pass an hsbvalues array parameter, pass null. In both the parameter and the return value, the three components are placed in the array as follows:
hsbvalues contains hue
hsbvalues contains saturation
hsbvalues contains brightness
public static Color getHSBColor (float hue, float saturation, float brightness):-The getHSBColor() method creates a Color object by using hue, saturation, and
brightness instead of red, green, and blue values.
Some other methods
public int hashCode ():- The hashCode() method returns a hash code for the color. The hash code is used whenever a color is used as a key in a Hashtable.
public boolean equals (Object o) :- The equals() method overrides the equals() method of the Object to define equality for Color objects. Two Color objects are equivalent if their red, green, and blue values are equal.
public String toString ():- The toString() method of Color returns a string showing the color's red, green, and blue settings.
For example System.out.println (Color.orange) would result in the following:
The AWT supports multiple type fonts. Within AWT, a font is specified by its name, style, and size. Each platform that supports Java provides a basic set of fonts. Beginning with Java 2, fonts have a family name, a logical font name, and a face name. The family name is the general name of the font, such as Courier. The logical name specifies a category of font, such as Monospaced. The face name specifies a specific font, such as Courier Italic.
An instance of the Font class represents a specific font to the system.
The Font class defines these variables:-
Variable --------------------> Meaning
1) protected String name ----------> Name of the font
2) protected int size ----------------> Size of the font in points
3) protected int style --------------> Font style
There are four styles for displaying fonts in Java: plain, bold, italic, and bold italic. Three class constants are used to represent font styles:
public static final int BOLD:- The BOLD constant represents a boldface font.
public static final int ITALIC :- The ITALIC constant represents an italic font.
public static final int PLAIN :- The PLAIN constant represents a plain or normal font.
The combination BOLD | ITALIC represents a bold italic font. PLAIN combined with either BOLD or ITALIC represents bold or italic, respectively.
public Font (String name, int style, int size) :- There is a single constructor for Font. It requires a name, style, and size. name argument represents the name of the font to create.
setFont (new Font ("TimesRoman", Font.BOLD | Font.ITALIC, 20));
public String getName () :-The getName() method returns the font's logical name. This is the name that is passed to the constructor when the instance of the Font is created.
public String getFamily () :- The getFamily() method returns the name of the font family to which the invoking font belongs.
public int getStyle () :- The getStyle() method returns the current style of the invoking font as an integer. It is convenient to use the isPlain(), isBold(), and isItalic() methods to find out the current style.
boolean isBold( )------> Returns true if the font includes the BOLD style value. Otherwise, false is returned.
boolean isItalic( )------> Returns true if the font includes the ITALIC style value. Otherwise, false is returned.
boolean isPlain( )------> Returns true if the font includes the PLAIN style value. Otherwise, false is returned.
public int getSize ():- The getSize() method returns the point size of the invoking font, as set by the size parameter in the constructor. The actual displayed size may be different.
public static Font getFont(String property) :- Returns the font associated with the system property specified by property. Null is returned if property does not exist.
public static Font getFont(String property, Font defaultFont):- Returns the font associated with the system property specified by property. The font specified by defaultFont is returned if property does not exist.
public int hashCode ():- The hashCode() method returns a hash code for the font. This hash code is used whenever a Font object is used as the key in a Hashtable.
public boolean equals (Object o):- The equals() method overrides the equals() method of Object to define equality for two Font objects. Two Font objects are equal if their size, style, and name are equal.
public String toString ():- The toString() method of Font returns a string showing the current family, name, style, and size settings.
Determining the Available Fonts
When working with fonts, we need to know which fonts are available on our machine. To know this, we can use the getAvailableFontFamilyNames( ) method defined by the GraphicsEnvironment class.
String[ ] getAvailableFontFamilyNames( ):-This method returns an array of strings that contains the names of the available font families.
In addition, the getAllFonts( ) method is defined by the GraphicsEnvironment class.
Font[ ] getAllFonts( ) :- This method returns an array of Font objects for all of the available fonts.
We need a Graphics Environment reference to call them as these are the members of Graphics Environment. We can obtain this reference by using the getLocalGraphicsEnvironment( ) static method, which is defined by GraphicsEnvironment.
static GraphicsEnvironment getLocalGraphicsEnvironment( )
Here is an example that illustrates the above concept:
Another Example illustrating Fonts:-
Re: Basic Graphics In Java With Examples (Part-2)
Nominate this article for Article of the month - Apr 2010
|All times are GMT +5.5. The time now is 12:47.|