google search

Wednesday, October 6, 2010

Sutherland–Hodgman algorithm

The algorithm begins with an input list of all vertices in the subject polygon. Next, one side of the clip polygon is extended infinitely in both directions, and the path of the subject polygon is traversed. Vertices from the input list are inserted into an output list if they lie on the visible side of the extended clip polygon line, and new vertices are added to the output list where the subject polygon path crosses the extended clip polygon line.
This process is repeated iteratively for each clip polygon side, using the output list from one stage as the input list for the next. Once all sides of the clip polygon have been processed, the final generated list of vertices defines a new single polygon that is entirely visible. Note that if the subject polygon was concave at vertices outside the clipping polygon, the new polygon may have coincident (i.e. overlapping) edges – this is acceptable for rendering, but not for other applications such as computing shadows.


PSEUDO CODE:-
List outputList = subjectPolygon;
  for (Edge clipEdge in clipPolygon) do
     List inputList = outputList;
     outputList.clear();
     Point S = inputList.last;
     for (Point E in inputList) do
        if (E inside clipEdge) then
           if (S not inside clipEdge) then
              outputList.add(ComputeIntersection(S,E,clipEdge));
           end if
           outputList.add(E);
        else if (S inside clipEdge) then
           outputList.add(ComputeIntersection(S,E,clipEdge));
        end if
        S = E;
     done
  done


Read more...

CLIPPING PLANE

Clipping planes can be used in addition of those used created for the viewing volume. OpenGL define 6 clipping plane GL_CLIP_PLANEi (i goes from 0 to 5).
A clipping plane is a plane that separate the space in two regions. One region is included from the viewing volume, the other is excluded.

In mathematics, a plane is defined by this equation :
    a*x+b*y+c*z+d = 0
(x, y, z) are the coordinates of the points in the 3D space. All points that verify this equation are on the plane.
The inequality (< or > instead of =) define the region in each side of the plane.

In OpenGL, a clipping plane is the region defined by this equation :
    a*x+b*y+c*z+d >= 0
A clipping plane is creates with the 4 values a, b, c & d likethis :
    double[] eq = {a, b, c, d}
    gl.glClipPlane(GL_CLIP_PLANEieq)    

All points draw , the other are excluded (will not be rendered on the screen).

Like for lights, clipping planes have to be enable to be active :
    gl.glEnable(GL_CLIP_PLANEi) 

Read more...

ORTHOGRAPHIC PROJECTION

The Viewing Volume shape in this case is a parallelepiped. The 6 clipping planes delimiting the space can be created with the aid of :
    gl.glOrtho(leftrightbottomtopnearfar)



VIEW VOLUME LOOKS LIKE:-




Read more...

PERSPECTIVE PROJECTION

With this kind of projection, the viewing volume shape is a truncated pyramid (its top is cutted).

This shape is abtained by 6 cutting planes : front, back, right, left, top and bottom planes (planes at the volume boundary). These planes are commonly called Clipping Planes. These planes can be created with the aid of the method :
    glu.gluPerspective(fovyaspectnearfar)
The fovy parameter is the angle between the plane that goes downwards and the plane that goes upwards.
The aspect ratio is generaly the aspect ratio of the window (window is the region of the screen in which the scene is rendered).




Read more...

VIEWING VOLUME

The 3D space is defined by 3 axis (vectors) : X, Y and Z. These 3 axis creates an axis system (see Tutorial 4for a representation of this axis system). All points of the 3D space can be expressed as a linear combination of these vectors. A point is point represented by its coordinates (x, y, z), which means x * X + y * Y + z * Z (upper case is a vector, low case is a scalar). The volume of the entire 3D space is infinity.

The Viewing Volume delimites the 3D space by creating a closed volume. Points outside this volume will not appears on the screen.
This particularity explain the first call glTranslate (just after glLoadIdentity) : we go inside the Viewing Volume. At start, we are on the front plane of the viewing volume.

The Viewing Volume can be created with two different kind of projections :
    Perspective Projection  Render object affected by the distance, a car is seen smaller when it move away.
    Orthographic Projection Render object NOT affected by the distance like a menu, a text on the screen, 2D objects ...

Read more...

Tuesday, October 5, 2010

CLIPPING ALGORITHMS

• Clipping eliminates the parts of a scene that aren’t going to be visible in the
final display.

• Clipping can be applied to various types of graphics objects.
– Points – this is basically trivial; check to see that the point coordinates are
between the clipping boundaries.
– Lines
– Fill Areas
– Curves
– Text

• The first three are standard in graphics packages.

• Most of the algorithms apply to rectangular clipping regions

Read more...

MODIFYING WINDOW PROPERTIES

• You can control how the window is reshaped by defining a reshape function
and setting it as the reshape callback using
glutReshapeFunc( winReshapeFunc);

• You can modify the size and shape of the current window using
glutPositionWindow( xNewTopLeft, yNewTopLeft);
glutReshapeWindow( newWidth, newHeight);

• Change the window title with
glutSetWindowTitle( newTitle);

• Specify the cursor with
glutSetCursorShape( shape);
Use symbolic constants like GLUT_CURSOR_UP_DOWN to specify the shapes. (Exact
shapes available are system specific.)

Read more...

USING MULTIPLE WINDOWS

• Create multiple windows by doing the same sequence of steps for each window.

• You need to keep track of the window ID to be able to go back to a particular
window.
glutSetWindow(windowID);
is used to make a particular window active.

• You can destroy a window when you are done with it.
glutDestroyWindow( windowID);

• The current window ID can be obtained using
glutGetWindow();

Read more...

DISPLAY WINDOWS IN OPEN GL

• Don’t forget to initialize GLUT with glutInit.

• Create a window of specified size in a particular position on the screen with
glutInitWindowPosition( xTopLeft, yTopLeft);
glutInitWindowSize( dwWidth, dwHeight);
glutCreateWindow( "Title");

• Default position is (−1,−1) which allows the window system to choose the
position.

• Default size is 300 pixels square.

• glutCreateWindow returns an integer id for the window. You only need this
if you are displaying more than one window.

Read more...

VIEWPORTS IN OPEN GL

• To specify the viewport parameters, do
glViewport( xvmin, yvmin, vpWidth, vpHeight)
with parameters given in integer screen coordinates. The first two give the
position of the lower left corner relative to the lower left corner of the display
window.

• By default, the viewport is the entire window. window.

• You can create multiple viewports within a window.

• To get the parameters for the active viewport, use
glGetIntegerv( GL_VIEWPORT, vpArray);
where vpArray is a 4 element integer array. The contents of vpArray after
the function returns will be the same as the arguments given to glViewport
in the same order

Read more...

2D VIEWING IN OPEN GL

• The basic library does everything in 3D.
– The 3D routines can be adapted to 2D
– A viewport function is provided.

• To define clipping windows and viewports, first go to projection mode.
glMatrixMode( GL_PROJECTION);
If necessary, use glLoadIdentity to initialize the matrix.

• A 2D clipping window can be defined with
gluOtrho2D( xwmin,xwmax, ywmin,ywmax)

• Normalized coordinates are from −1 to 1 in OpenGL. This is the default
clipping window.

Read more...

2D RENDERING PIPELINE

Read more...

2D VIEWING TRANSFORMATION

Read more...

2D COORDINATE SYSTEM

• We use modeling coordinates for individual parts of a 2D scene. For example,
your polygon function put the polygon at the origin with a “radius” of 1.
Those were modeling coordinates.

• World coordinates are used for organizing the parts into a scene.

• View coordinates are the coordinates within the desired viewport which is
somewhere within the window you are using.

• Normalized coordinates are between 0 and 1 or -1 and 1 in each direction.
They are used to make the viewing process independent of the output device.

• Device coordinates are relative to the actual display area on whatever device
you are using.

Read more...

2D TRANSFORMATIONS

The ability to perform transformations on objects in an image is an important feature of a graphics system. Operators were added to this system which allow the user to create 2D transformation matrices that perform the following transformations:

  • scale around (0, 0)
  • scale around an arbitrary point, with the x-scale direction oriented to a specified angle
  • translate
  • rotate around (0, 0)
  • rotate around an arbitrary point
In addition, helper functions were created that perform matrix multiplication, reset a matrix to the identity, reset a matrix to the zero matrix, and print a matrix. Below are some sample images created using these methods. The original polygons are in red, and the tranformed ones are in blue. The images are of translation, rotation of PI/4 about (0, 0), rotation of PI/4 about (80, 40), scaling by .8 in x and y, and respectively.

Read more...

Monday, October 4, 2010

3D AND ANIMATION


3D computer graphics

3D computer graphics in contrast to 2D computer graphics are graphics that use a three-dimensional representation of geometric data that is stored in the computer for the purposes of performing calculations and rendering 2D images. Such images may be for later display or for real-time viewing.
Despite these differences, 3D computer graphics rely on many of the same algorithms as 2D computer vector graphics in the wire frame model and 2D computer raster graphics in the final rendered display. In computer graphics software, the distinction between 2D and 3D is occasionally blurred; 2D applications may use 3D techniques to achieve effects such as lighting, and primarily 3D may use 2D rendering techniques.
3D computer graphics are often referred to as 3D models. Apart from the rendered graphic, the model is contained within the graphical data file. However, there are differences. A 3D model is the mathematical representation of any three-dimensional object. A model is not technically a graphic until it is visually displayed. Due to 3D printing, 3D models are not confined to virtual space. A model can be displayed visually as a two-dimensional image through a process called 3D rendering, or used in non-graphical computer simulations and calculations.


Computer animation

Computer animation is the art of creating moving images via the use of computers. It is a subfield of computer graphics and animation. Increasingly it is created by means of 3D computer graphics, though 2D computer graphics are still widely used for stylistic, low bandwidth, and faster real-time rendering needs. Sometimes the target of the animation is the computer itself, but sometimes the target is another medium, such as film. It is also referred to as CGI (Computer-generated imagery or computer-generated imaging), especially when used in films.
Virtual entities may contain and be controlled by assorted attributes, such as transform values (location, orientation, and scale) stored in an object's transformation matrix. Animation is the change of an attribute over time. Multiple methods of achieving animation exist; the rudimentary form is based on the creation and editing of keyframes, each storing a value at a given time, per attribute to be animated. The 2D/3D graphics software will interpolate between keyframes, creating an editable curve of a value mapped over time, resulting in animation. Other methods of animation include procedural and expression-based techniques: the former consolidates related elements of animated entities into sets of attributes, useful for creating particle effects and crowd simulations; the latter allows an evaluated result returned from a user-defined logical expression, coupled with mathematics, to automate animation in a predictable way (convenient for controlling bone behavior beyond what a hierarchy offers in skeletal system set up).
To create the illusion of movement, an image is displayed on the computer screen then quickly replaced by a new image that is similar to the previous image, but shifted slightly. This technique is identical to the illusion of movement in television and motion pictures.

Read more...

2D COMPUTER GRAPHICS


 
 
2D computer graphics are the computer-based generation of digital images—mostly from two-dimensional models, such as 2D geometric models, text, and digital images, and by techniques specific to them. The word may stand for the branch of computer science that comprises such techniques, or for the models themselves.
2D computer graphics are mainly used in applications that were originally developed upon traditional printing and drawing technologies, such as typography, cartography, technical drawing, advertising, etc.. In those applications, the two-dimensional image is not just a representation of a real-world object, but an independent artifact with added semantic value; two-dimensional models are therefore preferred, because they give more direct control of the image than 3D computer graphics, whose approach is more akin to photographythan to typography.


Pixel art

Pixel art is a form of digital art, created through the use of raster graphics software, where images are edited on the pixel level. Graphics in most old (or relatively limited) computer and video games, graphing calculator games, and many mobile phone games are mostly pixel art.


Vector graphics

Vector graphics formats are complementary to raster graphics, which is the representation of images as an array of pixels, as it is typically used for the representation of photographic images. There are instances when working with vector tools and formats is best practice, and instances when working with raster tools and formats is best practice. There are times when both formats come together. An understanding of the advantages and limitations of each technology and the relationship between them is most likely to result in efficient and effective use of tools.

Read more...

COMPUTER GRAPHICS


The term computer graphics has been used in a broad sense to describe "almost everything on computers that is not text or sound". Typically, the termcomputer graphics refers to several different things:
  • the representation and manipulation of image data by a computer
  • the various technologies used to create and manipulate images
  • the images so produced, and
  • the sub-field of computer science which studies methods for digitally synthesizing and manipulating visual content, see study of computer graphics
Compute graphics is the life line of today's computer world. Today, computers and computer-generated images touch many aspects of daily life. Computer imagery is found on television, in newspapers, for example in weather reports, or for example in all kinds of medical investigation and surgical procedures. A well-constructed graph can present complex statistics in a form that is easier to understand and interpret. In the media "such graphs are used to illustrate papers, reports, theses", and other presentation material.
Many powerful tools have been developed to visualize data. Computer generated imagery can be categorized into several different types: 2D, 3D, 5D, and animated graphics. As technology has improved, 3D computer graphics have become more common, but 2D computer graphics are still widely used. Computer graphics has emerged as a sub-field of computer science which studies methods for digitally synthesizing and manipulating visual content. Over the past decade, other specialized fields have been developed like information visualization, and scientific visualization more concerned with "the visualization of three dimensional phenomena (architectural, meteorological, medical, biological, etc.), where the emphasis is on realistic renderings of volumes, surfaces, illumination sources, and so forth, perhaps with a dynamic (time) component".

Read more...

Tuesday, April 27, 2010

configuring settings of java

Start the Java Plug-in Control Panel by following these instructions: 

  1. Click the Start menu
  2. Select Settings
  3. Select Control Panel
  4. Double click the Java icon.
  5. Click on the Network Settings button.

Network Settings dialog box
  1. Select the Use Browser Settings checkbox.
  2. Click the OK button to save your changes.Network Settings for the Java Control Panel
    1. Close all browser windows. Restart the browser and try to load the applet.
    2. If the applet still does not load and you see the same connection error, try to configure your web browser's proxy settings.

Read more...

common runtime error

Common Runtime Error Question

Level: Beginner
Focus: Basic concepts, runtime errors
Here’s a piece of code that has been saved in a file called "JollyMessage.java":
 // A jolly message is written to the screen!
 class Jollymessage 
 {
 
    public static void main(String[] args) {
 
      //Write the message to the terminal window
      System.out.println("Ho Ho Ho!");
 
    }
 }
 
The above code will produce a runtime error message. To put it another way, a mistake has been made but it won’t be picked up when the program is compiled, only when it is run. What is the mistake and what error will be returned when the compiled code is executed?

Read more...

what do i get when java software is downloaded

The Java Runtime Environment (JRE) is what you get when you download Java software. The JRE consists of the Java Virtual Machine (JVM), Java platform core classes, and supporting Java platform libraries. The JRE is the runtime portion of Java software, which is all you need to run it in your Web browser. When you download Java software, you only get what you need - no spyware, and no viruses.

Read more...

java definition


Java is a programming language and computing platform first released by Sun Microsystems in 1995. It is the underlying technology that powers state-of-the-art programs including utilities, games, and business applications. Java runs on more than 850 million personal computers worldwide, and on billions of devices worldwide, including mobile and TV devices.
Why do I need Java?
There are lots of applications and websites that won't work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere!
Why should I upgrade to the latest Java version?
The latest Java version contains important enhancements to improve performance, stability and security of the Java applications that run on your machine. Installing this free update will ensure that your Java applications continue to run safely and efficiently.

Read more...

Sunday, April 18, 2010

USING BEAN DEVELOPER KIT (BDK)

The Bean Developer Kit (BDK), available from the JavaSoft site, is a simple example
of a tool that enables you to create, configure, and connect a set of Beans. There is
also a set of sample Beans with their source code. This section provides step-by-step
instructions for installing and using this tool. Remember, the BDK is for use with
versions of Java 2 prior to 1.4.
INSTALLING BDK

The Java 2 SDK must be installed on your machine for the BDK to work. Confirm that
the SDK tools are accessible from your environment.
The BDK can then be downloaded from the JavaSoft site (http://java.sun.com). It is
packaged as one file that is a self-extracting archive. Follow the instructions to install
it on your machine. The discussion that follows assumes that the BDK is installed in a directory called bdk. If this is not the case with your system, substitute the proper
directory.

Starting the BDK
To start the BDK, follow these steps:
1. Change to the directory c:\bdk\beanbox.
2. Execute the batch file called run.bat. This causes the BDK to display the three
windows shown in Figure 25-1. ToolBox lists all of the different Beans that have
been included with the BDK. BeanBox provides an area to lay out and connect
the Beans selected from the ToolBox. Properties provides the ability to configure
a selected Bean. You may also see a window called Method Tracer, but we
won’t be using it.

Using the BDK
This section describes how to create an application by using some of the Beans
provided with the BDK. First, the Molecule Bean displays a three-dimensional view of
a molecule. It may be configured to present one of the following molecules: hyaluronic
acid, benzene, buckminsterfullerine, cyclohexane, ethane, or water. This component
also has methods that allow the molecule to be rotated in space along its X or Y axis Second, the OurButton Bean provides a push-button functionality. We will have one
button labeled “Rotate X” to rotate the molecule along its X axis and another button
labeled “Rotate Y” to rotate the molecule along its Y axis.

Read more...

APPLICATION BUILDER TOOLS

When working with Java Beans, most developers use an application builder tool, a utility
that enables you to configure a set of Beans, connect them together, and produce a
working application. In general, Bean builder tools have the following capabilities.
■ A palette is provided that lists all of the available Beans. As additional Beans
are developed or purchased, they can be added to the palette.
■ A worksheet is displayed that allows the designer to lay out Beans in a graphical
user interface. A designer may drag and drop a Bean from the palette to this
worksheet.
■ Special editors and customizers allow a Bean to be configured. This is the
mechanism by which the behavior of a Bean may be adapted for a particular
environment.
■ Commands allow a designer to inquire about the state and behavior of a
Bean. This information automatically becomes available when a Bean is added
to the palette.
■ Capabilities exist to interconnect Beans. This means that events generated by
one component are mapped to method invocations on other components.

■ When a collection of Beans has been configured and connected, it is possible to
save all of this information in a persistent storage area. At a later time, this
information can then be used to restore the state of the application.
Sun provides two Bean application builder tools. The first is the BeanBox, which is
part of the Bean Developers Kit (BDK). The BDK is the original builder tool provided
by Sun. The second is the new Bean Builder. Because Bean Builder is designed to
supplant the BeanBox, Sun has stopped development of the BDK and all new Bean
applications will be created using Bean Builder.
Although Bean Builder is the future of Bean development, it is not the sole focus of
this chapter. Instead, both BeanBox and Bean Builder are discussed. The reason for this
is that Bean Builder requires Java 2, version 1.4. It is incompatible with earlier versions
of Java 2. This means that readers of this book using Java 2, version 1.2 or version 1.3
will not be able to use Bean Builder. Instead, they must continue to use the BDK. Further,
readers using version 1.4 cannot use the BDK because it is not compatible with Java 2,
version 1.4. So, if you are using version 1.4, then you must use Bean Builder. If you are
using a version of Java prior to 1.4, you must use the BDK. Thus, both approaches are
described here, beginning with the BDK. Keep in mind that the information about Beans,
Bean architecture, JAR files, and so on, apply to either Bean development tool.
One other point: At the time of this writing, Java 2, version 1.4 is a released product,
but Bean Builder is currently in beta testing.

Read more...

ADVANTAGES OF JAVA BEANS


A software component architecture provides standard mechanisms to deal with
software building blocks. The following list enumerates some of the specific benefits
that Java technology provides for a component developer:
■ A Bean obtains all the benefits of Java’s “write-once, run-anywhere” paradigm.
■ The properties, events, and methods of a Bean that are exposed to an
application builder tool can be controlled.
■ A Bean may be designed to operate correctly in different locales, which makes it
useful in global markets.
■ Auxiliary software can be provided to help a person configure a Bean. This
software is only needed when the design-time parameters for that component
are being set. It does not need to be included in the run-time environment.
■ The configuration settings of a Bean can be saved in persistent storage and
restored at a later time.
■ A Bean may register to receive events from other objects and can generate
events that are sent to other objects.

Read more...

JAVA BEANS

A Java Bean is a software component that has been designed to be reusable in a variety
of different environments. There is no restriction on the capability of a Bean. It may
perform a simple function, such as checking the spelling of a document, or a complex
function, such as forecasting the performance of a stock portfolio. A Bean may be
visible to an end user. One example of this is a button on a graphical user interface.
A Bean may also be invisible to a user. Software to decode a stream of multimedia
information in real time is an example of this type of building block. Finally, a Bean
may be designed to work autonomously on a user’s workstation or to work in
cooperation with a set of other distributed components. Software to generate a pie
chart from a set of data points is an example of a Bean that can execute locally.
However, a Bean that provides real-time price information from a stock or
commodities exchange would need to work in cooperation with other distributed
software to obtain its data.
You will see shortly what specific changes a software developer must make to a
class so that it is usable as a Java Bean. However, one of the goals of the Java designers
was to make it easy to use this technology. Therefore, the code changes are minimal.

Read more...

Thursday, April 15, 2010

LAYOUT MANAGERS

Here, layoutObj is a reference to the desired layout manager. If you wish to disable the
layout manager and position components manually, pass null for layoutObj. If you do
this, you will need to determine the shape and position of each component manually,
using the setBounds( ) method defined by Component. Normally, you will want to
use a layout manager.
Each layout manager keeps track of a list of components that are stored by their
names. The layout manager is notified each time you add a component to a container.
Whenever the container needs to be resized, the layout manager is consulted via its
minimumLayoutSize( ) and preferredLayoutSize( ) methods. Each component
that is being managed by a layout manager contains the getPreferredSize( ) and
getMinimumSize( ) methods. These return the preferred and minimum size required
to display each component. The layout manager will honor these requests if at all
possible, while maintaining the integrity of the layout policy. You may override
these methods for controls that you subclass. Default values are provided otherwise.
Java has several predefined LayoutManager classes, several of which are described
next. You can use the layout manager that best fits your application.
FlowLayout
FlowLayout is the default layout manager. This is the layout manager that the preceding
examples have used. FlowLayout implements a simple layout style, which is similar to
how words flow in a text editor. Components are laid out from the upper-left corner, left
to right and top to bottom. When no more components fit on a line, the next one appears
on the next line. A small space is left between each component, above and below, as well
as left and right. Here are the constructors for FlowLayout:
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
The first form creates the default layout, which centers components and leaves five
pixels of space between each component. The second form lets you specify how each
line is aligned. Valid values for how are as follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
These values specify left, center, and right alignment, respectively. The third form
allows you to specify the horizontal and vertical space left between components in
horz and vert, respectively.
Here is a version of the CheckboxDemo applet shown earlier in this chapter,
modified so that it uses left-aligned flow layout.

// Use left-aligned flow layout.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*


*/
public class FlowLayoutDemo extends Applet
implements ItemListener {
String msg = "";
Checkbox Win98, winNT, solaris, mac;
public void init() {
// set left-aligned flow layout
setLayout(new FlowLayout(FlowLayout.LEFT));
Win98 = new Checkbox("Windows 98/XP", null, true);
winNT = new Checkbox("Windows NT/2000");
solaris = new Checkbox("Solaris");
mac = new Checkbox("MacOS");
add(Win98);
add(winNT);
add(solaris);
add(mac);
// register to receive item events
Win98.addItemListener(this);
winNT.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
// Repaint when status of a check box changes.
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current state of the check boxes.
public void paint(Graphics g) {

msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows 98/XP: " + Win98.getState();
g.drawString(msg, 6, 100);
msg = " Windows NT/2000: " + winNT.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac: " + mac.getState();
g.drawString(msg, 6, 160);
}
}

BorderLayout
The BorderLayout class implements a common layout style for top-level windows. It
has four narrow, fixed-width components at the edges and one large area in the center.
The four sides are referred to as north, south, east, and west. The middle area is called
the center. Here are the constructors defined by BorderLayout:
BorderLayout( )
BorderLayout(int horz, int vert)

The first form creates a default border layout. The second allows you to specify the
horizontal and vertical space left between components in horz and vert, respectively.
BorderLayout defines the following constants that specify the regions:
BorderLayout.CENTER BorderLayout.SOUTH
BorderLayout.EAST BorderLayout.WEST
BorderLayout.NORTH
When adding components, you will use these constants with the following form of
add( ), which is defined by Container:
void add(Component compObj, Object region);
Here, compObj is the component to be added, and region specifies where the component
will be added.
Here is an example of a BorderLayout with a component in each layout area:
// Demonstrate BorderLayout.
import java.awt.*;
import java.applet.*;
import java.util.*;
/*


*/
public class BorderLayoutDemo extends Applet {
public void init() {
setLayout(new BorderLayout());
add(new Button("This is across the top."),
BorderLayout.NORTH);
add(new Label("The footer message might go here."),
BorderLayout.SOUTH);
add(new Button("Right"), BorderLayout.EAST);
add(new Button("Left"), BorderLayout.WEST);
String msg = "The reasonable man adapts " +
"himself to the world;\n" +
"the unreasonable one persists in " +
"trying to adapt the world to himself.\n" +

"Therefore all progress depends " +
"on the unreasonable man.\n\n" +
" - George Bernard Shaw\n\n";
add(new TextArea(msg), BorderLayout.CENTER);
}
}

Using Insets
Sometimes you will want to leave a small amount of space between the container
that holds your components and the window that contains it. To do this, override
the getInsets( ) method that is defined by Container. This function returns an Insets
object that contains the top, bottom, left, and right inset to be used when the container
is displayed. These values are used by the layout manager to inset the components
when it lays out the window. The constructor for Insets is shown here:
Insets(int top, int left, int bottom, int right)
The values passed in top, left, bottom, and right specify the amount of space between the
container and its enclosing window.

The getInsets( ) method has this general form:
Insets getInsets( )
When overriding one of these methods, you must return a new Insets object that contains
the inset spacing you desire.
Here is the preceding BorderLayout example modified so that it insets its components
ten pixels from each border. The background color has been set to cyan to help make the
insets more visible.
// Demonstrate BorderLayout with insets.
import java.awt.*;
import java.applet.*;
import java.util.*;
/*


*/
public class InsetsDemo extends Applet {
public void init() {
// set background color so insets can be easily seen
setBackground(Color.cyan);
setLayout(new BorderLayout());
add(new Button("This is across the top."),
BorderLayout.NORTH);
add(new Label("The footer message might go here."),
BorderLayout.SOUTH);
add(new Button("Right"), BorderLayout.EAST);
add(new Button("Left"), BorderLayout.WEST);
String msg = "The reasonable man adapts " +
"himself to the world;\n" +
"the unreasonable one persists in " +
"trying to adapt the world to himself.\n" +
"Therefore all progress depends " +
"on the unreasonable man.\n\n" +
" - George Bernard Shaw\n\n";
add(new TextArea(msg), BorderLa
yout.CENTER);
}

// add insets
public Insets getInsets() {
return new Insets(10, 10, 10, 10);
}
}

GridLayout
GridLayout lays out components in a two-dimensional grid. When you instantiate
a GridLayout, you define the number of rows and columns. The constructors
supported by GridLayout are shown here:
GridLayout( )
GridLayout(int numRows, int numColumns )
GridLayout(int numRows, int numColumns, int horz, int vert)
The first form creates a single-column grid layout. The second form creates a grid
layout with the specified number of rows and columns. The third form allows you
to specify the horizontal and vertical space left between components in horz and vert,
respectively. Either numRows or numColumns can be zero. Specifying numRows as zero
allows for unlimited-length columns. Specifying numColumns as zero allows for
unlimited-length rows.

Here is a sample program that creates a 4×4 grid and fills it in with 15 buttons, each
labeled with its index:
// Demonstrate GridLayout
import java.awt.*;
import java.applet.*;
/*


*/
public class GridLayoutDemo extends Applet {
static final int n = 4;
public void init() {
setLayout(new GridLayout(n, n));
setFont(new Font("SansSerif", Font.BOLD, 24));
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
int k = i * n + j;
if(k > 0)
add(new Button("" + k));
}
}
}
}

CardLayout
The CardLayout class is unique among the other layout managers in that it stores
several different layouts. Each layout can be thought of as being on a separate index
card in a deck that can be shuffled so that any card is on top at a given time. This can
be useful for user interfaces with optional components that can be dynamically enabled
and disabled upon user input. You can prepare the other layouts and have them hidden,
ready to be activated when needed.
CardLayout provides these two constructors:
CardLayout( )
CardLayout(int horz, int vert)
The first form creates a default card layout. The second form allows you to specify the
horizontal and vertical space left between components in horz and vert, respectively.
Use of a card layout requires a bit more work than the other layouts. The cards are
typically held in an object of type Panel. This panel must have CardLayout selected as
its layout manager. The cards that form the deck are also typically objects of type Panel.
Thus, you must create a panel that contains the deck and a panel for each card in the deck.
Next, you add to the appropriate panel the components that form each card. You then add
these panels to the panel for which CardLayout is the layout manager. Finally, you add this
panel to the main applet panel. Once these steps are complete, you must provide some
way for the user to select between cards. One common approach is to include one push
button for each card in the deck.
When card panels are added to a panel, they are usually given a name. Thus, most
of the time, you will use this form of add( ) when adding cards to a panel:
void add(Component panelObj, Object name);
Here, name is a string that specifies the name of the card whose panel is specified
by panelObj.
After you have created a deck, your program activates a card by calling one of the
following methods defined by CardLayout:
void first(Container deck)
void last(Container deck)
void next(Container deck)
void previous(Container deck)
void show(Container deck, String cardName)
Here, deck is a reference to the container (usually a panel) that holds the cards, and
cardName is the name of a card. Calling first( ) causes the first card in the deck to be shown. To show the last card, call last( ). To show the next card, call next( ). To show
the previous card, call previous( ). Both next( ) and previous( ) automatically cycle
back to the top or bottom of the deck, respectively. The show( ) method displays the
card whose name is passed in cardName.
The following example creates a two-level card deck that allows the user to select
an operating system. Windows-based operating systems are displayed in one card.
Macintosh and Solaris are displayed in the other card.
// Demonstrate CardLayout.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*


*/
public class CardLayoutDemo extends Applet
implements ActionListener, MouseListener {
Checkbox Win98, winNT, solaris, mac;
Panel osCards;
CardLayout cardLO;
Button Win, Other;
public void init() {
Win = new Button("Windows");
Other = new Button("Other");
add(Win);
add(Other);
cardLO = new CardLayout();
osCards = new Panel();
osCards.setLayout(cardLO); // set panel layout to card layout
Win98 = new Checkbox("Windows 98/XP", null, true);
winNT = new Checkbox("Windows NT/2000");
solaris = new Checkbox("Solaris");
mac = new Checkbox("MacOS");
// add Windows check boxes to a panel
Panel winPan = new Panel();

winPan.add(Win98);
winPan.add(winNT);
// Add other OS check boxes to a panel
Panel otherPan = new Panel();
otherPan.add(solaris);
otherPan.add(mac);
// add panels to card deck panel
osCards.add(winPan, "Windows");
osCards.add(otherPan, "Other");
// add cards to main applet panel
add(osCards);
// register to receive action events
Win.addActionListener(this);
Other.addActionListener(this);
// register mouse events
addMouseListener(this);
}
// Cycle through panels.
public void mousePressed(MouseEvent me) {
cardLO.next(osCards);
}
// Provide empty implementations for the other MouseListener methods.
public void mouseClicked(MouseEvent me) {
}
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
public void mouseReleased(MouseEvent me) {
}
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == Win) {

cardLO.show(osCards, "Windows");
}
else {
cardLO.show(osCards, "Other");
}
}
}

Read more...

TEXT AREA

Sometimes a single line of text input is not enough for a given task. To handle these
situations, the AWT includes a simple multiline editor called TextArea. Following are
the constructors for TextArea:
TextArea( )
TextArea(int numLines, int numChars)
TextArea(String str)
TextArea(String str, int numLines, int numChars)
TextArea(String str, int numLines, int numChars, int sBars)
Here, numLines specifies the height, in lines, of the text area, and numChars specifies its
width, in characters. Initial text can be specified by str. In the fifth form you can specify
the scroll bars that you want the control to have. sBars must be one of these values:
SCROLLBARS_BOTH SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY SCROLLBARS_VERTICAL_ONLY
TextArea is a subclass of TextComponent. Therefore, it supports the getText( ), setText( ),
getSelectedText( ), select( ), isEditable( ), and setEditable( ) methods described in the
preceding section.

TextArea adds the following methods:
void append(String str)
void insert(String str, int index)
void replaceRange(String str, int startIndex, int endIndex)
The append( ) method appends the string specified by str to the end of the current
text. insert( ) inserts the string passed in str at the specified index. To replace text,
call replaceRange( ). It replaces the characters from startIndex to endIndex–1, with
the replacement text passed in str.
Text areas are almost self-contained controls. Your program incurs virtually no
management overhead. Text areas only generate got-focus and lost-focus events.
Normally, your program simply obtains the current text when it is needed.
The following program creates a TextArea control:
// Demonstrate TextArea.
import java.awt.*;
import java.applet.*;
/*


*/
public class TextAreaDemo extends Applet {
public void init() {
String val = "There are two ways of constructing " +
"a software design.\n" +
"One way is to make it so simple\n" +
"that there are obviously no deficiencies.\n" +
"And the other way is to make it so complicated\n" +
"that there are no obvious deficiencies.\n\n" +
" -C.A.R. Hoare\n\n" +
"There's an old story about the person who wished\n" +
"his computer were as easy to use as his telephone.\n" +
"That wish has come true,\n" +
"since I no longer know how to use my telephone.\n\n" +
" -Bjarne Stroustrup, AT&T, (inventor of C++)";
TextArea text = new TextArea(val, 10, 30);
add(text);
}
}

Read more...

  © Blogger templates ProBlogger Template by Ourblogtemplates.com 2008

Back to TOP