google search

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

TEXT FIELDS

The TextField class implements a single-line text-entry area, usually called an edit control.
Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and
paste keys, and mouse selections. TextField is a subclass of TextComponent. TextField
defines the following constructors:
TextField( )
TextField(int numChars)
TextField(String str)
TextField(String str, int numChars)
The first version creates a default text field. The second form creates a text field that
is numChars characters wide. The third form initializes the text field with the string
contained in str. The fourth form initializes a text field and sets its width.
TextField (and its superclass TextComponent) provides several methods that allow
you to utilize a text field. To obtain the string currently contained in the text field, call
getText( ). To set the text, call setText( ). These methods are as follows:
String getText( )
void setText(String str)
Here, str is the new string.

The user can select a portion of the text in a text field. Also, you can select a portion
of text under program control by using select( ). Your program can obtain the currently
selected text by calling getSelectedText( ). These methods are shown here:
String getSelectedText( )
void select(int startIndex, int endIndex)
getSelectedText( ) returns the selected text. The select( ) method selects the characters
beginning at startIndex and ending at endIndex–1.
You can control whether the contents of a text field may be modified by the user
by calling setEditable( ). You can determine editability by calling isEditable( ). These
methods are shown here:
boolean isEditable( )
void setEditable(boolean canEdit)
isEditable( ) returns true if the text may be changed and false if not. In setEditable( ),
if canEdit is true, the text may be changed. If it is false, the text cannot be altered.
There may be times when you will want the user to enter text that is not displayed,
such as a password. You can disable the echoing of the characters as they are typed
by calling setEchoChar( ). This method specifies a single character that the TextField
will display when characters are entered (thus, the actual characters typed will not be
shown). You can check a text field to see if it is in this mode with the echoCharIsSet( )
method. You can retrieve the echo character by calling the getEchoChar( ) method.
These methods are as follows:
void setEchoChar(char ch)
boolean echoCharIsSet( )
char getEchoChar( )
Here, ch specifies the character to be echoed.
Handling a TextField
Since text fields perform their own editing functions, your program generally will not
respond to individual key events that occur within a text field. However, you may want
to respond when the user presses ENTER. When this occurs, an action event is generated.
Here is an example that creates the classic user name and password screen:
// Demonstrate text field.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*



*/
public class TextFieldDemo extends Applet
implements ActionListener {
TextField name, pass;
public void init() {
Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
name = new TextField(12);
pass = new TextField(8);
pass.setEchoChar('?');
add(namep);
add(name);
add(passp);
add(pass);
// register to receive action events
name.addActionListener(this);
pass.addActionListener(this);
}
// User pressed Enter.
public void actionPerformed(ActionEvent ae) {
repaint();
}
public void paint(Graphics g) {
g.drawString("Name: " + name.getText(), 6, 60);
g.drawString("Selected text in name: "
+ name.getSelectedText(), 6, 80);
g.drawString("Password: " + pass.getText(), 6, 100);
}
}

Read more...

SCROLL BARS

Scroll bars are used to select continuous values between a specified minimum and
maximum. Scroll bars may be oriented horizontally or vertically. A scroll bar is actually
a composite of several individual parts. Each end has an arrow that you can click to move
the current value of the scroll bar one unit in the direction of the arrow. The current value
of the scroll bar relative to its minimum and maximum values is indicated by the slider box
(or thumb) for the scroll bar. The slider box can be dragged by the user to a new position.
The scroll bar will then reflect this value. In the background space on either side of the thumb, the user can click to cause the thumb to jump in that direction by some increment
larger than 1. Typically, this action translates into some form of page up and page down.
Scroll bars are encapsulated by the Scrollbar class.
Scrollbar defines the following constructors:
Scrollbar( )
Scrollbar(int style)
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
The first form creates a vertical scroll bar. The second and third forms allow you to
specify the orientation of the scroll bar. If style is Scrollbar.VERTICAL, a vertical scroll
bar is created. If style is Scrollbar.HORIZONTAL, the scroll bar is horizontal. In the
third form of the constructor, the initial value of the scroll bar is passed in initialValue.
The number of units represented by the height of the thumb is passed in thumbSize.
The minimum and maximum values for the scroll bar are specified by min and max.
If you construct a scroll bar by using one of the first two constructors, then you
need to set its parameters by using setValues( ), shown here, before it can be used:
void setValues(int initialValue, int thumbSize, int min, int max)
The parameters have the same meaning as they have in the third constructor just
described.
To obtain the current value of the scroll bar, call getValue( ). It returns the current
setting. To set the current value, call setValue( ). These methods are as follows:
int getValue( )
void setValue(int newValue)
Here, newValue specifies the new value for the scroll bar. When you set a value, the
slider box inside the scroll bar will be positioned to reflect the new value.
You can also retrieve the minimum and maximum values via getMinimum( ) and
getMaximum( ), shown here:
int getMinimum( )
int getMaximum( )
They return the requested quantity.
By default, 1 is the increment added to or subtracted from the scroll bar each
time it is scrolled up or down one line. You can change this increment by calling
setUnitIncrement( ). By default, page-up and page-down increments are 10. You can
change this value by calling setBlockIncrement( ). These methods are shown here:
void setUnitIncrement(int newIncr)
void setBlockIncrement(int newIncr)

Handling Scroll Bars
To process scroll bar events, you need to implement the AdjustmentListener interface.
Each time a user interacts with a scroll bar, an AdjustmentEvent object is generated.
Its getAdjustmentType( ) method can be used to determine the type of the adjustment.
The types of adjustment events are as follows:
BLOCK_DECREMENT A page-down event has been generated.
BLOCK_INCREMENT A page-up event has been generated.
TRACK An absolute tracking event has been generated.
UNIT_DECREMENT The line-down button in a scroll bar has been pressed.
UNIT_INCREMENT The line-up button in a scroll bar has been pressed.
The following example creates both a vertical and a horizontal scroll bar. The
current settings of the scroll bars are displayed. If you drag the mouse while inside
the window, the coordinates of each drag event are used to update the scroll bars.
An asterisk is displayed at the current drag position.
// Demonstrate scroll bars.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*


*/
public class SBDemo extends Applet
implements AdjustmentListener, MouseMotionListener {
String msg = "";
Scrollbar vertSB, horzSB;
public void init() {
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
vertSB = new Scrollbar(Scrollbar.VERTICAL,
0, 1, 0, height);
horzSB = new Scrollbar(Scrollbar.HORIZONTAL,
0, 1, 0, width);

add(vertSB);
add(horzSB);
// register to receive adjustment events
vertSB.addAdjustmentListener(this);
horzSB.addAdjustmentListener(this);
addMouseMotionListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent ae) {
repaint();
}
// Update scroll bars to reflect mouse dragging.
public void mouseDragged(MouseEvent me) {
int x = me.getX();
int y = me.getY();
vertSB.setValue(y);
horzSB.setValue(x);
repaint();
}
// Necessary for MouseMotionListener
public void mouseMoved(MouseEvent me) {
}
// Display current value of scroll bars.
public void paint(Graphics g) {
msg = "Vertical: " + vertSB.getValue();
msg += ", Horizontal: " + horzSB.getValue();
g.drawString(msg, 6, 160);
// show current mouse drag position
g.drawString("*", horzSB.getValue(),
vertSB.getValue());
}
}

Read more...

USING LISTS

The List class provides a compact, multiple-choice, scrolling selection list. Unlike the
Choice object, which shows only the single selected item in the menu, a List object can
be constructed to show any number of choices in the visible window. It can also be
created to allow multiple selections. List provides these constructors:
List( )
List(int numRows)
List(int numRows, boolean multipleSelect)
The first version creates a List control that allows only one item to be selected at any
one time. In the second form, the value of numRows specifies the number of entries in
the list that will always be visible (others can be scrolled into view as needed). In the
third form, if multipleSelect is true, then the user may select two or more items at a time.
If it is false, then only one item may be selected.
To add a selection to the list, call add( ). It has the following two forms:
void add(String name)
void add(String name, int index)
Here, name is the name of the item added to the list. The first form adds items to the
end of the list. The second form adds the item at the index specified by index. Indexing
begins at zero. You can specify –1 to add the item to the end of the list.
For lists that allow only single selection, you can determine which item is currently
selected by calling either getSelectedItem( ) or getSelectedIndex( ). These methods are
shown here:
String getSelectedItem( )
int getSelectedIndex( )
The getSelectedItem( ) method returns a string containing the name of the item. If
more than one item is selected or if no selection has yet been made, null is returned.
getSelectedIndex( ) returns the index of the item. The first item is at index 0. If more
than one item is selected, or if no selection has yet been made, –1 is returned.
For lists that allow multiple selection, you must use either getSelectedItems( ) or
getSelectedIndexes( ), shown here, to determine the current selections:
String[ ] getSelectedItems( )
int[ ] getSelectedIndexes( )
getSelectedItems( ) returns an array containing the names of the currently selected
items. getSelectedIndexes( ) returns an array containing the indexes of the currently
selected items.

To obtain the number of items in the list, call getItemCount( ). You can set the
currently selected item by using the select( ) method with a zero-based integer index.
These methods are shown here:
int getItemCount( )
void select(int index)
Given an index, you can obtain the name associated with the item at that index by
calling getItem( ), which has this general form:
String getItem(int index)
Here, index specifies the index of the desired item.
Handling Lists
To process list events, you will need to implement the ActionListener interface.
Each time a List item is double-clicked, an ActionEvent object is generated. Its
getActionCommand( ) method can be used to retrieve the name of the newly selected
item. Also, each time an item is selected or deselected with a single click, an ItemEvent
object is generated. Its getStateChange( ) method can be used to determine whether a
selection or deselection triggered this event. getItemSelectable( ) returns a reference
to the object that triggered this event.
Here is an example that converts the Choice controls in the preceding section into
List components, one multiple choice and the other single choice:
// Demonstrate Lists.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*


*/
public class ListDemo extends Applet implements ActionListener {
List os, browser;
String msg = "";
public void init() {
os = new List(4, true);
browser = new List(4, false);

// add items to os list
os.add("Windows 98/XP");
os.add("Windows NT/2000");
os.add("Solaris");
os.add("MacOS");
// add items to browser list
browser.add("Netscape 3.x");
browser.add("Netscape 4.x");
browser.add("Netscape 5.x");
browser.add("Netscape 6.x");
browser.add("Internet Explorer 4.0");
browser.add("Internet Explorer 5.0");
browser.add("Internet Explorer 6.0");
browser.add("Lynx 2.4");
browser.select(1);
// add lists to window
add(os);
add(browser);
// register to receive action events
os.addActionListener(this);
browser.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
repaint();
}
// Display current selections.
public void paint(Graphics g) {
int idx[];
msg = "Current OS: ";
idx = os.getSelectedIndexes();
for(int i=0; i
msg += os.getItem(idx[i]) + " ";

g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
}
}

Read more...

CHOICE CONTROLS

The Choice class is used to create a pop-up list of items from which the user may
choose. Thus, a Choice control is a form of menu. When inactive, a Choice component
takes up only enough space to show the currently selected item. When the user clicks
on it, the whole list of choices pops up, and a new selection can be made. Each item
in the list is a string that appears as a left-justified label in the order it is added to the
Choice object. Choice only defines the default constructor, which creates an empty list.
To add a selection to the list, call add( ). It has this general form:
void add(String name)
Here, name is the name of the item being added. Items are added to the list in the order
in which calls to add( ) occur.
To determine which item is currently selected, you may call either getSelectedItem( )
or getSelectedIndex( ). These methods are shown here:
String getSelectedItem( )
int getSelectedIndex( )
The getSelectedItem( ) method returns a string containing the name of the item.
getSelectedIndex( ) returns the index of the item. The first item is at index 0. By
default, the first item added to the list is selected.
To obtain the number of items in the list, call getItemCount( ). You can set the
currently selected item using the select( ) method with either a zero-based integer
index or a string that will match a name in the list. These methods are shown here:
int getItemCount( )
void select(int index)
void select(String name)
Given an index, you can obtain the name associated with the item at that index by
calling getItem( ), which has this general form:
String getItem(int index)
Here, index specifies the index of the desired item.
Handling Choice Lists
Each time a choice is selected, an item event is generated. This is sent to any listeners
that previously registered an interest in receiving item event notifications from that
component. Each listener implements the ItemListener interface. That interface defines
the itemStateChanged( ) method. An ItemEvent object is supplied as the argument to
this method.

Here is an example that creates two Choice menus. One selects the operating
system. The other selects the browser.
// Demonstrate Choice lists.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*


*/
public class ChoiceDemo extends Applet implements ItemListener {
Choice os, browser;
String msg = "";
public void init() {
os = new Choice();
browser = new Choice();
// add items to os list
os.add("Windows 98/XP");
os.add("Windows NT/2000");
os.add("Solaris");
os.add("MacOS");
// add items to browser list
browser.add("Netscape 3.x");
browser.add("Netscape 4.x");
browser.add("Netscape 5.x");
browser.add("Netscape 6.x");
browser.add("Internet Explorer 4.0");
browser.add("Internet Explorer 5.0");
browser.add("Internet Explorer 6.0");
browser.add("Lynx 2.4");
browser.select("Netscape 4.x");
// add choice lists to window
add(os);

add(browser);
// register to receive item events
os.addItemListener(this);
browser.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current selections.
public void paint(Graphics g) {
msg = "Current OS: ";
msg += os.getSelectedItem();
g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
}
}

Read more...

CHECK BOX GROUP

It is possible to create a set of mutually exclusive check boxes in which one and only one
check box in the group can be checked at any one time. These check boxes are often called
radio buttons, because they act like the station selector on a car radio—only one station can be selected at any one time. To create a set of mutually exclusive check boxes, you must
first define the group to which they will belong and then specify that group when you
construct the check boxes. Check box groups are objects of type CheckboxGroup. Only
the default constructor is defined, which creates an empty group.
You can determine which check box in a group is currently selected by calling
getSelectedCheckbox( ). You can set a check box by calling setSelectedCheckbox( ).
These methods are as follows:
Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox which)
Here, which is the check box that you want to be selected. The previously selected check
box will be turned off.
Here is a program that uses check boxes that are part of a group:
// Demonstrate check box group.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*


*/
public class CBGroup extends Applet implements ItemListener {
String msg = "";
Checkbox Win98, winNT, solaris, mac;
CheckboxGroup cbg;
public void init() {
cbg = new CheckboxGroup();
Win98 = new Checkbox("Windows 98/XP", cbg, true);
winNT = new Checkbox("Windows NT/2000", cbg, false);
solaris = new Checkbox("Solaris", cbg, false);
mac = new Checkbox("MacOS", cbg, false);
add(Win98);
add(winNT);
add(solaris);
add(mac);
Win98.addItemListener(this);

winNT.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current state of the check boxes.
public void paint(Graphics g) {
msg = "Current selection: ";
msg += cbg.getSelectedCheckbox().getLabel();
g.drawString(msg, 6, 100);
}
}

Read more...

APPLYING CHECK BOXES

A check box is a control that is used to turn an option on or off. It consists of a small box
that can either contain a check mark or not. There is a label associated with each check
box that describes what option the box represents. You change the state of a check box
by clicking on it. Check boxes can be used individually or as part of a group. Check
boxes are objects of the Checkbox class.
Checkbox supports these constructors:
Checkbox( )
Checkbox(String str)
Checkbox(String str, boolean on)
Checkbox(String str, boolean on, CheckboxGroup cbGroup)
Checkbox(String str, CheckboxGroup cbGroup, boolean on)
The first form creates a check box whose label is initially blank. The state of the check
box is unchecked. The second form creates a check box whose label is specified by str.
The state of the check box is unchecked. The third form allows you to set the initial
state of the check box. If on is true, the check box is initially checked; otherwise, it is
cleared. The fourth and fifth forms create a check box whose label is specified by str
and whose group is specified by cbGroup. If this check box is not part of a group, then
cbGroup must be null. (Check box groups are described in the next section.) The value
of on determines the initial state of the check box.
To retrieve the current state of a check box, call getState( ). To set its state, call
setState( ). You can obtain the current label associated with a check box by calling
getLabel( ). To set the label, call setLabel( ). These methods are as follows:
boolean getState( )
void setState(boolean on)
String getLabel( )
void setLabel(String str)
Here, if on is true, the box is checked. If it is false, the box is cleared. The string passed
in str becomes the new label associated with the invoking check box.
Handling Check Boxes
Each time a check box is selected or deselected, an item event is generated. This is sent to
any listeners that previously registered an interest in receiving item event notifications
from that component. Each listener implements the ItemListener interface. That interface defines the itemStateChanged( ) method. An ItemEvent object is supplied as the argument
to this method. It contains information about the event (for example, whether it was
a selection or deselection).
The following program creates four check boxes. The initial state of the first box is
checked. The status of each check box is displayed. Each time you change the state of
a check box, the status display is updated.
// Demonstrate check boxes.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*


*/
public class CheckboxDemo extends Applet implements ItemListener {
String msg = "";
Checkbox Win98, winNT, solaris, mac;
public void init() {
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);
Win98.addItemListener(this);
winNT.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
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 = " MacOS: " + mac.getState();
g.drawString(msg, 6, 160);
}
}

Read more...

BUTTONS

USING BUTTONS

The most widely used control is the push button. A push button is a component that
contains a label and that generates an event when it is pressed. Push buttons are objects
of type Button. Button defines these two constructors:
Button( )
Button(String str)
The first version creates an empty button. The second creates a button that contains str
as a label.
After a button has been created, you can set its label by calling setLabel( ). You can
retrieve its label by calling getLabel( ). These methods are as follows:
void setLabel(String str)
String getLabel( )
Here, str becomes the new label for the button.
Handling Buttons
Each time a button is pressed, an action event is generated. This is sent to any listeners
that previously registered an interest in receiving action event notifications from that
component. Each listener implements the ActionListener interface. That interface defines
the actionPerformed( ) method, which is called when an event occurs. An ActionEvent
object is supplied as the argument to this method. It contains both a reference to the button
that generated the event and a reference to the string that is the label of the button. Usually,
either value may be used to identify the button, as you will see.
Here is an example that creates three buttons labeled “Yes,” “No,” and “Undecided.”
Each time one is pressed, a message is displayed that reports which button has been pressed. In this version, the label of the button is used to determine which button has
been pressed. The label is obtained by calling the getActionCommand( ) method on the
ActionEvent object passed to actionPerformed( ).
// Demonstrate Buttons
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*


*/
public class ButtonDemo extends Applet implements ActionListener {
String msg = "";
Button yes, no, maybe;
public void init() {
yes = new Button("Yes");
no = new Button("No");
maybe = new Button("Undecided");
add(yes);
add(no);
add(maybe);
yes.addActionListener(this);
no.addActionListener(this);
maybe.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
if(str.equals("Yes")) {
msg = "You pressed Yes.";
}
else if(str.equals("No")) {
msg = "You pressed No.";
}
else {
msg = "You pressed Undecided.";
}

repaint();
}
public void paint(Graphics g) {
g.drawString(msg, 6, 100);
}
}

Read more...

LABELS

The easiest control to use is a label. A label is an object of type Label, and it contains a
string, which it displays. Labels are passive controls that do not support any interaction
with the user. Label defines the following constructors:
Label( )
Label(String str)
Label(String str, int how)
The first version creates a blank label. The second version creates a label that contains
the string specified by str. This string is left-justified. The third version creates a label that
contains the string specified by str using the alignment specified by how. The value of how
must be one of these three constants: Label.LEFT, Label.RIGHT, or Label.CENTER.

You can set or change the text in a label by using the setText( ) method. You can
obtain the current label by calling getText( ). These methods are shown here:
void setText(String str)
String getText( )
For setText( ), str specifies the new label. For getText( ), the current label is returned.
You can set the alignment of the string within the label by calling setAlignment( ).
To obtain the current alignment, call getAlignment( ). The methods are as follows:
void setAlignment(int how)
int getAlignment( )
Here, how must be one of the alignment constants shown earlier.
The following example creates three labels and adds them to an applet:
// Demonstrate Labels
import java.awt.*;
import java.applet.*;
/*


*/
public class LabelDemo extends Applet {
public void init() {
Label one = new Label("One");
Label two = new Label("Two");
Label three = new Label("Three");
// add labels to applet window
add(one);
add(two);
add(three);
}
}

Read more...

ADDING AND REMOVING CONTROLS

To include a control in a window, you must add it to the window. To do this, you must
first create an instance of the desired control and then add it to a window by calling add( ),which is defined by Container. The add( ) method has several forms. The following form
is the one that is used for the first part of this chapter:
Component add(Component compObj)
Here, compObj is an instance of the control that you want to add. A reference to
compObj is returned. Once a control has been added, it will automatically be visible
whenever its parent window is displayed.
Sometimes you will want to remove a control from a window when the control is
no longer needed. To do this, call remove( ). This method is also defined by Container.
It has this general form:
void remove(Component obj)
Here, obj is a reference to the control you want to remove. You can remove all controls
by calling removeAll( ).

Read more...

CONTROL FUNDAMENTALS

The AWT supports the following types of controls:
■ Labels
■ Push buttons
■ Check boxes
■ Choice lists
■ Lists
■ Scroll bars
■ Text editing
These controls are subclasses of Component

Read more...

Wednesday, April 14, 2010

SETTING PAINT MODE

The paint mode determines how objects are drawn in a window. By default, new output
to a window overwrites any preexisting contents. However, it is possible to have new
objects XORed onto the window by using setXORMode( ), as follows:
void setXORMode(Color xorColor)
Here, xorColor specifies the color that will be XORed to the window when an object is
drawn. 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.
To return to overwrite mode, call setPaintMode( ), shown here:
void setPaintMode( )
In general, you will want to use overwrite mode for normal output, and XOR mode for
special purposes. For example, the following program displays cross hairs that track
the mouse pointer. The cross hairs are XORed onto the window and are always visible,
no matter what the underlying color is.

// Demonstrate XOR mode.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*


*/
public class XOR extends Applet {
int chsX=100, chsY=100;
public XOR() {
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent me) {
int x = me.getX();
int y = me.getY();
chsX = x-10;
chsY = y-10;
repaint();
}
});
}
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);
// xor cross hairs
g.setXORMode(Color.black);
g.drawLine(chsX-10, chsY, chsX+10, chsY);

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

Read more...

COLOR METHODS

The Color class defines several methods that help manipulate colors. They are
examined here.
Using Hue, Saturation, and Brightness
The hue-saturation-brightness (HSB) color model is an alternative to red-green-blue
(RGB) for specifying particular colors. Figuratively, hue is a wheel of color. The hue is
specified with a number between 0.0 and 1.0 (the colors are approximately: red, orange,
yellow, green, blue, indigo, and violet). Saturation is another scale ranging from 0.0 to
1.0, representing light pastels to intense hues. Brightness values also range from 0.0 to
1.0, where 1 is bright white and 0 is black. Color supplies two methods that let you
convert between RGB and HSB. They are shown here:
static int HSBtoRGB(float hue, float saturation, float brightness)
static float[ ] RGBtoHSB(int red, int green, int blue, float values[ ])
HSBtoRGB( ) returns a packed RGB value compatible with the Color(int) constructor.
RGBtoHSB( ) returns a float array of HSB values corresponding to RGB integers. If
values is not null, then this array is given the HSB values and returned. Otherwise, a
new array is created and the HSB values are returned in it. In either case, the array
contains the hue at index 0, saturation at index 1, and brightness at index 2.
getRed( ), getGreen( ), getBlue( )
You can obtain the red, green, and blue components of a color independently using
getRed( ), getGreen( ), and getBlue( ), shown here:
int getRed( )
int getGreen( )
int getBlue( )

Each of these methods returns the RGB color component found in the invoking Color
object in the lower 8 bits of an integer.
getRGB( )
To obtain a packed, RGB representation of a color, use getRGB( ), shown here:
int getRGB( )
The return value is organized as described earlier.
Setting the Current Graphics Color
By default, graphics objects are drawn in the current foreground color. You can change
this color by calling the Graphics method setColor( ):
void setColor(Color newColor)
Here, newColor specifies the new drawing color.
You can obtain the current color by calling getColor( ), shown here:
Color getColor( )
A Color Demonstration Applet
The following applet constructs several colors and draws various objects using
these colors:
// Demonstrate color.
import java.awt.*;
import java.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);
}
}

Read more...

WORKING WITH COLORS

Java supports color in a portable, device-independent fashion. 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.
Thus, your code does not need to be concerned with the differences in the way color is
supported by various hardware devices. Color is encapsulated by the Color class.
As you saw in Chapter 19, Color defines several constants (for example, Color.black)
to specify a number of common 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)
Color(int rgbValue)
Color(float red, float green, float blue)
The first constructor takes three integers that specify the color as a mix of red, green,
and blue. These values must be between 0 and 255.

The second color constructor takes a single integer that contains the mix of red, green,
and blue packed into an integer. The integer is organized with red in bits 16 to 23,
green in bits 8 to 15, and blue in bits 0 to 7. Here is an example of this constructor:
int newRed = (0xff000000 | (0xc0 << 16) | (0x00 << 8) | 0x00);
Color darkRed = new Color(newRed);
The final constructor, Color(float, float, float), takes three float values (between 0.0
and 1.0) that specify the relative mix of red, green, and blue.
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
described in Chapter 19. You can also select it as the current drawing color.

Read more...

WORKING WITH GRAPHICS

The AWT supports a rich assortment of graphics methods. All graphics are drawn
relative to a window. This can be the main window of an applet, a child window of
an applet, or a stand-alone application window. The origin of each window is at the
top-left corner and is 0,0. Coordinates are specified in pixels. All output to a window
takes place through a graphics context. A graphics context is encapsulated by the
Graphics class and is obtained in two ways:
■ It is passed to an applet when one of its various methods, such as paint( ) or
update( ), is called.
■ It is returned by the getGraphics( ) method of Component.
For the remainder of the examples in this chapter, we will be demonstrating
graphics in the main applet window. However, the same techniques will apply to any
other window.
The Graphics class defines a number of drawing functions. Each shape can be
drawn edge-only or filled. Objects are drawn and filled in the currently selected
graphics color, which is black by default. When a graphics object is drawn that exceeds
the dimensions of the window, output is automatically clipped. Let’s take a look at
several of the drawing methods.

Drawing Lines
Lines are drawn by means of the drawLine( ) method, shown here:
void drawLine(int startX, int startY, int endX, int endY)
drawLine( ) displays a line in the current drawing color that begins at startX,startY and
ends at endX,endY.
The following applet draws several lines:
// Draw lines
import java.awt.*;
import java.applet.*;
/*



*/
public class Lines extends Applet {
public void paint(Graphics g) {
g.drawLine(0, 0, 100, 100);
g.drawLine(0, 100, 100, 0);
g.drawLine(40, 25, 250, 180);
g.drawLine(75, 90, 400, 400);
g.drawLine(20, 150, 400, 40);
g.drawLine(5, 290, 80, 19);
}
}

Drawing Rectangles
The drawRect( ) and fillRect( ) methods display an outlined and filled rectangle,
respectively. They are shown here:
void drawRect(int top, int left, int width, int height)
void fillRect(int top, int left, int width, int height)
The upper-left corner of the rectangle is at top,left. The dimensions of the rectangle are
specified by width and height.
To draw a rounded rectangle, use drawRoundRect( ) or fillRoundRect( ), both
shown here:
void drawRoundRect(int top, int left, int width, int height,
int xDiam, int yDiam)

Drawing Ellipses and Circles
To draw an ellipse, use drawOval( ). To fill an ellipse, use fillOval( ). These methods
are shown here:
void drawOval(int top, int left, int width, int height)
void fillOval(int top, int left, int width, int height)
The ellipse is drawn within a bounding rectangle whose upper-left corner is specified
by top,left and whose width and height are specified by width and height.
To draw a circle, specify a square as the bounding rectangle.

Drawing Arcs
Arcs can be drawn with drawArc( ) and fillArc( ), shown here:
void drawArc(int top, int left, int width, int height, int startAngle,
int sweepAngle)
void fillArc(int top, int left, int width, int height, int startAngle,
int sweepAngle)
The arc is bounded by the rectangle whose upper-left corner is specified by top,left
and whose width and height are specified by width and height. The arc is drawn from
startAngle through the angular distance specified by sweepAngle. Angles are specified
in degrees. Zero degrees is on the horizontal, at the three o’clock position. The arc is
drawn counterclockwise if sweepAngle is positive, and clockwise if sweepAngle is
negative. Therefore, to draw an arc from twelve o’clock to six o’clock, the start angle
would be 90 and the sweep angle 180.

Drawing Polygons
It is possible to draw arbitrarily shaped figures using drawPolygon( ) and fillPolygon( ),
shown here:
void drawPolygon(int x[ ], int y[ ], int numPoints)
void fillPolygon(int x[ ], int y[ ], int numPoints)
The polygon’s endpoints are specified by the coordinate pairs contained within the x and
y arrays. The number of points defined by x and y is specified by numPoints. There are
alternative forms of these methods in which the polygon is specified by a Polygon object.

Read more...

CREATING A WINDOW PROGRAM

Although creating applets is the most common use for Java’s AWT, it is possible to
create stand-alone AWT-based applications, too. To do this, simply create an instance
of the window or windows you need inside main( ). For example, the following
program creates a frame window that responds to mouse clicks and keystrokes:
// Create an AWT-based application.
import java.awt.*;

import java.awt.event.*;
import java.applet.*;
// Create a frame window.
public class AppWindow extends Frame {
String keymsg = "This is a test.";
String mousemsg = "";
int mouseX=30, mouseY=30;
public AppWindow() {
addKeyListener(new MyKeyAdapter(this));
addMouseListener(new MyMouseAdapter(this));
addWindowListener(new MyWindowAdapter());
}
public void paint(Graphics g) {
g.drawString(keymsg, 10, 40);
g.drawString(mousemsg, mouseX, mouseY);
}
// Create the window.
public static void main(String args[]) {
AppWindow appwin = new AppWindow();
appwin.setSize(new Dimension(300, 200));
appwin.setTitle("An AWT-Based Application");
appwin.setVisible(true);
}
}
class MyKeyAdapter extends KeyAdapter {
AppWindow appWindow;
public MyKeyAdapter(AppWindow appWindow) {
this.appWindow = appWindow;
}
public void keyTyped(KeyEvent ke) {
appWindow.keymsg += ke.getKeyChar();
appWindow.repaint();
};
}
class MyMouseAdapter extends MouseAdapter {

AppWindow appWindow;
public MyMouseAdapter(AppWindow appWindow) {
this.appWindow = appWindow;
}
public void mousePressed(MouseEvent me) {
appWindow.mouseX = me.getX();
appWindow.mouseY = me.getY();
appWindow.mousemsg = "Mouse Down at " + appWindow.mouseX +
", " + appWindow.mouseY;
appWindow.repaint();
}
}
class MyWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}

Read more...

HANDLING EVENTS IN FRAME WINDOW

Since Frame is a subclass of Component, it inherits all the capabilities defined by
Component. This means that you can use and manage a frame window that you create
just like you manage your applet’s main window. For example, you can override
paint( ) to display output, call repaint( ) when you need to restore the window, and
override all event handlers. Whenever an event occurs in a window, the event handlers
defined by that window will be called. Each window handles its own events. For
example, the following program creates a window that responds to mouse events.
The main applet window also responds to mouse events. When you experiment
with this program, you will see that mouse events are sent to the window in which
the event occurs.
// Handle mouse events in both child and applet windows.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*


*/
// Create a subclass of Frame.
class SampleFrame extends Frame
implements MouseListener, MouseMotionListener {
String msg = "";
int mouseX=10, mouseY=40;
int movX=0, movY=0;

SampleFrame(String title) {
super(title);
// register this object to receive its own mouse events
addMouseListener(this);
addMouseMotionListener(this);
// create an object to handle window events
MyWindowAdapter adapter = new MyWindowAdapter(this);
// register it to receive those events
addWindowListener(adapter);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
}
// Handle mouse entered.
public void mouseEntered(MouseEvent evtObj) {
// save coordinates
mouseX = 10;
mouseY = 54;
msg = "Mouse just entered child.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent evtObj) {
// save coordinates
mouseX = 10;
mouseY = 54;
msg = "Mouse just left child window.";
repaint();
}
// Handle mouse pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle mouse released.

public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
movX = me.getX();
movY = me.getY();
msg = "*";
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// save coordinates
movX = me.getX();
movY = me.getY();
repaint(0, 0, 100, 60);
}
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
g.drawString("Mouse at " + movX + ", " + movY, 10, 40);
}
}
class MyWindowAdapter extends WindowAdapter {
SampleFrame sampleFrame;
public MyWindowAdapter(SampleFrame sampleFrame) {
this.sampleFrame = sampleFrame;
}
public void windowClosing(WindowEvent we) {
sampleFrame.setVisible(false);
}
}

// Applet window.
public class WindowEvents extends Applet
implements MouseListener, MouseMotionListener {
SampleFrame f;
String msg = "";
int mouseX=0, mouseY=10;
int movX=0, movY=0;
// Create a frame window.
public void init() {
f = new SampleFrame("Handle Mouse Events");
f.setSize(300, 200);
f.setVisible(true);
// register this object to receive its own mouse events
addMouseListener(this);
addMouseMotionListener(this);
}
// Remove frame window when stopping applet.
public void stop() {
f.setVisible(false);
}
// Show frame window when starting applet.
public void start() {
f.setVisible(true);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 24;
msg = "Mouse just entered applet window.";
repaint();

}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 24;
msg = "Mouse just left applet window.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
movX = me.getX();
movY = me.getY();
msg = "*";
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {

// save coordinates
movX = me.getX();
movY = me.getY();
repaint(0, 0, 100, 20);
}
// Display msg in applet window.
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
g.drawString("Mouse at " + movX + ", " + movY, 0, 10);
}
}

Read more...

  © Blogger templates ProBlogger Template by Ourblogtemplates.com 2008

Back to TOP