Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/articles/java-tutorials/)
-   -   Basic Graphics In Java With Examples (Part-2) (http://www.go4expert.com/articles/basic-graphics-java-examples-part-2-t21880/)

techgeek.in 24Apr2010 22:03

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.

Painting Mode



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:-

Code:

import java.awt.*;
import java applet.*;

/*
 <applet code="xor" width="200" height="200">
 </applet>
 */
 
public class xor extends Applet
{
  public void paint (Graphics g)
  {
    g.drawLine(0, 0, 100, 100);
    g.drawLine(0, 100, 100, 0);
    g.setColor(Color.blue);
    g.drawLine(40, 25, 250, 180);
    g.drawLine(75, 90, 400, 400);
    g.setColor(Color.green);
    g.drawRect(10, 10, 60, 50);
    g.fillRect(100, 10, 60, 50);
    g.setColor(Color.red);
    g.drawRoundRect(190, 10, 60, 50, 15, 15);
    g.fillRoundRect(70, 90, 140, 100, 30, 40);
    g.setColor(Color.cyan);
    g.drawLine(20, 150, 400, 40);
    g.drawLine(5, 290, 80, 19);
  }
}

Output is shown here:-
http://www.go4expert.com/images/arti...raphics/g2.jpg

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:-

http://www.go4expert.com/images/arti...aphics/g2b.jpg

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

Another Example:

The cross hairs are XORed onto the window and are always visible, no matter what the underlying color is.
Code:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="XOR1" width=400 height=200>
</applet>
*/
public class XOR1 extends Applet
{
  int chsX=100, chsY=100;
  public void paint(Graphics g)
  {
    g.setColor(Color.red);

    g.fillRoundRect(70, 90, 140, 100, 30, 40);
    g.setColor(Color.cyan);
    g.drawLine(20, 150, 400, 40);

    g.setXORMode(Color.black);
    g.drawLine(chsX-10, chsY, chsX+10, chsY);
    g.drawLine(chsX, chsY-10, chsX, chsY+10);
    g.setPaintMode();
  }
}

http://www.go4expert.com/images/arti...aphics/g2c.jpg

Working With Color



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:-

Code:

+-----------+------+--------+-------+---------+------------+------------+
| Color    | Red  | Green  | Blue  | Hue    | Saturation | Brightness |
+-----------+------+--------+-------+---------+------------+------------+
| black    |    0 |    0  |    0  |      0 |          0 |        0  |
| blue      |    0 |    0  |  255  | .666667 |          1 |        1  |
| cyan      |    0 |  255  |  255  |      .5 |          1 |        1  |
| darkGray  |  64 |    64  |  64  |      0 |          0 |  .25098  |
| gray      |  128 |  128  |  128  |      0 |          0 |  .501961  |
| green    |    0 |  255  |    0  | .333333 |          1 |        1  |
| lightGray |  192 |  192  |  192  |      0 |          0 |  .752941  |
| magenta  |  255 |    0  |  255  | .833333 |          1 |        1  |
| orange    |  255 |  200  |    0  | .130719 |          1 |        1  |
| pink      |  255 |  175  |  175  |      0 |    .313726 |        1  |
| red      |  255 |    0  |    0  |      0 |          1 |        1  |
| white    |  255 |  255  |  255  |      0 |          0 |        1  |
| yellow    |  255 |  255  |    0  | .166667 |          1 |        1  |
+-----------+------+--------+-------+---------+------------+------------+

These constants are used like any other class variable: for example, Color.red is a constant Color object representing the color red.

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

Color 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:
Code:

import java.awt.*;
import java.applet.*;
/*
<applet code="ColorDemo" width=300 height=200>
</applet>
*/
public class ColorDemo extends Applet
{
  // draw lines
  public void paint(Graphics g)
  {
    Color c1 = new Color(255, 100, 100);
    Color c2 = new Color(100, 255, 100);
    Color c3 = new Color(100, 100, 255);
    g.setColor(c1);
    g.drawLine(0, 0, 100, 100);
    g.drawLine(0, 100, 100, 0);
    g.setColor(c2);
    g.drawLine(40, 25, 250, 180);
    g.drawLine(75, 90, 400, 400);
    g.setColor(c3);
    g.drawLine(20, 150, 400, 40);
    g.drawLine(5, 290, 80, 19);
    g.setColor(Color.red);
    g.drawOval(10, 10, 50, 50);
    g.fillOval(70, 90, 140, 100);
    g.setColor(Color.blue);
    g.drawOval(190, 10, 90, 30);
    g.drawRect(10, 10, 60, 50);
    g.setColor(Color.cyan);
    g.fillRect(100, 10, 60, 50);
    g.drawRoundRect(190, 10, 60, 50, 15, 15);
  }
}

Output is as shown here:-

http://www.go4expert.com/images/arti...aphics/g2d.jpg

Hue, saturation, and brightness



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[0] contains hue
hsbvalues[1] contains saturation
hsbvalues[2] 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:

java.awt.Color[r=255,g=200,b=0]

Working with Fonts



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.

Example :
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.

For example:
java.awt.Font[family=TimesRoman,name=TimesRoman,style=bolditalic ,size=20]

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:
Code:

/*
<applet code="ShowFonts" width=550 height=60>
</applet>
*/
import java.applet.*;
import java.awt.*;
public class ShowFonts extends Applet
{
  public void paint(Graphics g)
  {
    String msg = "";
    String FontList[];
    GraphicsEnvironment ge =
    GraphicsEnvironment.getLocalGraphicsEnvironment();
    FontList = ge.getAvailableFontFamilyNames();
    for(int i = 0; i < FontList.length; i++)
    msg += FontList[i] + " ";
    g.drawString(msg, 4, 16);
  }
}

Output is shown here:
http://www.go4expert.com/images/arti...aphics/g2e.jpg

Another Example illustrating Fonts:-
Code:

import java.applet.*;
import java.awt.*;
/*
<applet code="FontInfo" width=350 height=60>
</applet>
*/
public class FontInfo extends Applet
{
  public void paint(Graphics g)
  {
    Font f = g.getFont();
    String fontName = f.getName();
    String fontFamily = f.getFamily();
    int fontSize = f.getSize();
    int fontStyle = f.getStyle();
    String msg = "Family: " + fontName;
    msg += ", Font: " + fontFamily;
    msg += ", Size: " + fontSize + ", Style: ";
    if((fontStyle & Font.BOLD) == Font.BOLD)
      msg += "Bold ";
    if((fontStyle & Font.ITALIC) == Font.ITALIC)
      msg += "Italic ";
    if((fontStyle & Font.PLAIN) == Font.PLAIN)
      msg += "Plain ";
    g.drawString(msg, 4, 16);
  }
}

Output:

http://www.go4expert.com/images/arti...aphics/g2f.jpg

shabbir 3May2010 13:15

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 19:32.