1 AWT Notes
1 AWT Notes
The Abstract Window Toolkit (AWT) was Java’s first GUI framework, and it has been part
of Java since version 1.0. It contains numerous classes and methods that allow you to create
windows and simple controls. A common use of the AWT is in applets, it is also used to create
stand-alone windows that run in a GUI environment, such as Windows.
AWT Classes
AWT classes are contained in the java.awt package. It is one of Java’s largest packages.
following Table lists AWT classes,
Class Description
AWTEvent Encapsulates AWT events.
AWTEventMulticaster Dispatches events to multiple listeners.
The border layout manager. Border layouts use five components:
BorderLayout
North, South, East, West, and Center.
Button Creates a push button control.
Canvas A blank, semantics-free window.
The card layout manager. Card layouts emulate index cards. Only the
CardLayout
one on top is showing.
Checkbox Creates a check box control.
CheckboxGroup Creates a group of check box controls.
CheckboxMenuItem Creates an on/off menu item.
Choice Creates a pop-up list.
Color Manages colors in a portable, platform-independent fashion.
Component An abstract superclass for various AWT components.
Container A subclass of Component that can hold other components.
Cursor Encapsulates a bitmapped cursor.
Dialog Creates a dialog window.
Specifies the dimensions of an object. The width is stored in width, and
Dimension
the height is stored in height.
EventQueue Queues events.
FileDialog Creates a window from which a file can be selected.
The flow layout manager. Flow layout positions components left to
FlowLayout
right, top to bottom.
Font Encapsulates a type font.
Encapsulates various information related to a font. This information
FontMetrics
helps you display text in a window.
Creates a standard window that has a title bar, resize corners, and a
Frame
menu bar.
Encapsulates the graphics context. This context is used by the various
Graphics
output methods to display output in a window.
Component:
At the top of the AWT hierarchy is the Component class. Component is an abstract
class that encapsulates all of the attributes of a visual component. Except for menus, all user
interface elements that are displayed on the screen and that interact with the user are
subclasses of Component. A Component object is responsible for remembering the current
foreground and background colors and the currently selected text font.
Container:
The Container class is a subclass of Component. It has additional methods
that allow other Component objects to be nested within it. A container is responsible for
laying out (that is, positioning) any components that it contains. It does this through the use
of various layout managers.
Panel:
The Panel class is a concrete subclass of Container. A Panel may be thought of as a
recursively nestable, concrete screen component. Panel is the superclass for Applet. When
screen output is directed to an applet, it is drawn on the surface of a Panel object.
In essence, a Panel is a window that does not contain a title bar, menu bar, or border.
This is why you don’t see these items when an applet is run inside a browser. When you run
an applet using an applet viewer, the applet viewer provides the title and border.
Window:
The Window class creates a top-level window. A top-level window is not contained
within any other object; it sits directly on the desktop. Generally, you won’t create
Window objects directly. Instead, you will use a subclass of Window called Frame
.
Frame:
Frame encapsulates what is commonly thought of as a ―window.‖ It is a subclass of
Window and has a title bar, menu bar, borders, and resizing corners.
Canvas:
Although it is not part of the hierarchy for applet or frame windows, there is one other
type of window that you will find valuable: Canvas. Derived from Component, Canvas
encapsulates a blank window upon which you can draw.
Notice that you cannot specify the dimensions of the window. Instead, you must set the size
of the window after it has been created. A HeadlessException is thrown if an attempt is made to
create a Frame instance in an environment that does not support user interaction.
There are several key methods you will use when working with Frame windows. They
are examined here.
The getSize( ) method is used to obtain the current size of a window. One of its forms is
shown here:
Dimension getSize( )
This method returns the current size of the window contained within the width and height
fields of a Dimension object.
The HeadlessException
When an attempt is made to instantiate a GUI component in a noninteractive environment
(such as one in which no display, mouse, or keyboard is present). You can use this exception to write
code that can adapt to non-interactive environments.
Here, compRef is a reference to the control you want to remove. You can remove all
controls by calling removeAll( ).
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.
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 window:
// Demonstrate Labels
import java.awt.*;
import java.applet.*;
/*
<applet code="LabelDemo" width=300 height=200>
</applet>
*/
public class LabelDemo extends Applet {
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( ) throws HeadlessException
Button(String str) throws HeadlessException
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.
// Demonstrate Buttons
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ButtonDemo" width=250 height=150>
</applet>
*/
public class ButtonDemo extends Applet implements ActionListener {
Button yes, no, maybe;
public void init() {
yes = new Button("Yes");
no = new Button("No");
maybe = new Button("Undecided");
}
}
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.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CheckboxDemo" width=240 height=200>
</applet>
*/
public class CheckboxDemo extends Applet implements ItemListener {
String msg = "";
Checkbox windows, android, solaris, mac;
public void init() {
windows = new Checkbox("Windows", null, true);
android = new Checkbox("Android");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
add(windows);
add(android);
add(solaris);
add(mac);
windows.addItemListener(this);
android.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: " + windows.getState();
g.drawString(msg, 6, 100);
msg = " Android: " + android.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac OS: " + mac.getState();
g.drawString(msg, 6, 160);
}
12 | P a g e Mr. Satish S. Ambulge (HOD, CO Dept, VAPM, Almala
Adv. Java Programming (22517): 1- Abstract Windowing Toolkit (AWT)
Teaching Hours - 8, Total Marks - 12 (R - 2, U - 4, A - 6)
CheckboxGroup
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( ).
Choice
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 defines only 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 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.
os = new Choice();
browser = new Choice();
// add items to os list
os.add("Windows");
os.add("Android");
os.add("Solaris");
os.add("Mac OS");
// add items to browser list
browser.add("Internet Explorer");
browser.add("Firefox");
browser.add("Chrome");
// 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);
}
}
List
The List class provides a compact, multiple-choice, scrolling selection list. 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( ) throws HeadlessException
List(int numRows) throws HeadlessException
List(int numRows, boolean multipleSelect) throws HeadlessException
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.
// Demonstrate Lists.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ListDemo" width=300 height=180> </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");
os.add("Android");
18 | P a g e Mr. Satish S. Ambulge (HOD, CO Dept, VAPM, Almala
Adv. Java Programming (22517): 1- Abstract Windowing Toolkit (AWT)
Teaching Hours - 8, Total Marks - 12 (R - 2, U - 4, A - 6)
os.add("Solaris");
os.add("Mac OS");
// add items to browser list
browser.add("Internet Explorer");
browser.add("Firefox");
browser.add("Chrome");
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<idx.length; i++)
msg += os.getItem(idx[i]) + " ";
g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
}
}
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)
TextField
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( ) throws HeadlessException
TextField(int numChars) throws HeadlessException
TextField(String str) throws HeadlessException
TextField(String str, int numChars) throws HeadlessException
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.
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. If ch is zero, then normal echoing is restored.
TextArea
AWT includes a simple multiline editor called TextArea. Following are
the constructors for TextArea:
TextArea( ) throws HeadlessException
TextArea(int numLines, int numChars) throws HeadlessException
TextArea(String str) throws HeadlessException
TextArea(String str, int numLines, int numChars) throws HeadlessException
TextArea(String str, int numLines, int numChars, int sBars) throws HeadlessException
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_HORIZON SCROLLBARS_VERTICA
TAL_ONLY L_ONLY
// Demonstrate TextArea.
import java.awt.*;
import java.applet.*;
/*
<applet code="TextAreaDemo" width=300 height=250> </applet>
*/
public class TextAreaDemo extends Applet {
public void init() {
String val = "Java 8 is the latest version of the most\n" + "widely-used computer language for
Internet programming.\n" + "Building on a rich heritage, Java has advanced both\n" + "the art and
science of computer language design.\n\n" + "One of the reasons for Java's ongoing success is its\n"
+ "constant, steady rate of evolution. Java has never stood\n" + "still. Instead, Java has consistently
adapted to the\n" + "rapidly changing landscape of the networked world.\n" + "Moreover, Java has
often led the way, charting the\n" + "course for others to follow.";
TextArea text = new TextArea(val, 10, 30);
add(text);
}
}
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.
FlowLayout
FlowLayout is the default layout manager. FlowLayout implements a simple layout
style, which is similar to how words flow in a text editor. The direction of the layout, by default, is
left to right, top to bottom.
Therefore, by default, components are laid out line-by-line beginning at the upper-left corner.
In all cases, when a line is filled, layout advances to 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
FlowLayout.LEADING
FlowLayout.TRAILING
The third constructor allows you to specify the horizontal and vertical space left between
components in horz and vert, respectively.
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 compRef, Object region)
Here, compRef is a reference to the component to be added, and region specifies where the
component will be added.
// Demonstrate BorderLayout.
import java.awt.*;
import java.applet.*;
import java.util.*;
/*
<applet code="BorderLayoutDemo" width=400 height=200> </applet>
*/
public class BorderLayoutDemo extends Applet {
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 unlimitedlength columns. Specifying numColumns as zero allows for unlimited-
length rows.
// Demonstrate GridLayout
import java.awt.*;
import java.applet.*;
/*
<applet code="GridLayoutDemo" width=300 height=200> </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. 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.
29 | P a g e Mr. Satish S. Ambulge (HOD, CO Dept, VAPM, Almala
Adv. Java Programming (22517): 1- Abstract Windowing Toolkit (AWT)
Teaching Hours - 8, Total Marks - 12 (R - 2, U - 4, A - 6)
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 window.
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 panelRef, Object name)
Here, name is a string that specifies the name of the card whose panel is specified by
panelRef.
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. The show( ) method displays the card whose name is passed in
cardName.
// Demonstrate CardLayout.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CardLayoutDemo" width=300 height=100>
</applet>
*/
public class CardLayoutDemo extends Applet implements ActionListener, MouseListener {
Checkbox windowsXP, windows7, windows8, android, 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
windowsXP = new Checkbox("Windows XP", null, true);
windows7 = new Checkbox("Windows 7", null, false);
windows8 = new Checkbox("Windows 8", null, false);
}
}
GridBagLayout
By using grid bag is that you can specify the relative placement of components by specifying their
positions within cells inside a grid. The key to the grid bag is that each component can be a different
size, and each row in the grid can have a different number of columns.
The location and size of each component in a grid bag are determined by a set of constraints
linked to it. The constraints are contained in an object of type GridBagConstraints. Constraints
include the height and width of a cell, and the placement of a component, its alignment, and its
anchor point within the cell.
The general procedure for using a grid bag is to first create a new GridBagLayout object
and to make it the current layout manager. Then, set the constraints that apply to each component
that will be added to the grid bag. Finally, add the components to the layout manager.
GridBagLayout defines only one constructor, which is shown here:
GridBagLayout( )
The key to successfully using GridBagLayout is the proper setting of the constraints, which
are stored in a GridBagConstraints object. GridBagConstraints defines several fields that you can
set to govern the size, placement, and spacing of a component.
Field Purpose
Specifies the location of a component within a cell. The default is
int anchor
GridBagConstraints.CENTER.
Specifies how a component is resized if the component is smaller than
its cell. Valid values are GridBagConstraints.NONE (the default),
int fill
GridBagConstraints.HORIZONTAL, GridBagConstraints.VERTICAL,
GridBagConstraints.BOTH.
int
Specifies the height of component in terms of cells. The default is 1.
gridheight
int Specifies the width of component in terms of cells. The default is 1.
gridwidth
Specifies the X coordinate of the cell to which the component will be added.
int gridx
The default value is GridBagConstraints.RELATIVE.
Specifies the Y coordinate of the cell to which the component will be added.
int gridy
The default value is GridBagConstraints.RELATIVE.
Insets
Specifies the insets. Default insets are all zero.
insets
Specifies extra horizontal space that surrounds a component within a cell.
int ipadx
The default is 0.
Specifies extra vertical space that surrounds a component within a cell. The
int ipady
default is 0.
Specifies a weight value that determines the horizontal spacing between cells
double and the edges of the container that holds them. The default value is 0.0. The
weightx greater the weight, the more space that is allocated. If all values are 0.0, extra
space is distributed evenly between the edges of the window
Specifies a weight value that determines the vertical spacing between cells
double and the edges of the container that holds them. The default value is 0.0. The
weighty greater the weight, the more space that is allocated. If all values are 0.0, extra
space is distributed evenly between the edges of the window
GridBagConstraints also defines several static fields that contain standard constraint values, such
as GridBagConstraints.CENTER and GridBagConstraints.VERTICAL.
When a component is smaller than its cell, you can use the anchor field to specify where
within the cell the component’s top-left corner will be located. There are three types of values that
you can give to anchor. The first are absolute:
GridBagConstraints.CENTER GridBagConstraints.SOUTH
GridBagConstraints.EAST GridBagConstraints.SOUTHEAST
GridBagConstraints.NORTH GridBagConstraints.SOUTHWEST
GridBagConstraints.NORTHEAST GridBagConstraints.WEST
GridBagConstraints.NORTHWEST
The second type of values that can be given to anchor is relative, which means the
values are relative to the container’s orientation, which might differ for non-Western
languages. The relative values are shown here:
GridBagConstraints.FIRST_LINE_END GridBagConstraints.LINE_END
GridBagConstraints.FIRST_LINE_START GridBagConstraints.LINE_START
GridBagConstraints.LAST_LINE_END GridBagConstraints.PAGE_END
GridBagConstraints.LAST_LINE_START GridBagConstraints.PAGE_START
The third type of values that can be given to anchor allows you to position components
relative to the baseline of the row. These values are shown here:
GridBagConstraints.BASELINE GridBagConstraints.BASELINE_LEADING
GridBagConstraints.BASELINE_TRAILING GridBagConstraints.ABOVE_BASELINE
GridBagConstraints.ABOVE_BASELINE_
GridBagConstraints.ABOVE_BASELINE_LEADING
TRAILING
33 | P a g e Mr. Satish S. Ambulge (HOD, CO Dept, VAPM, Almala
Adv. Java Programming (22517): 1- Abstract Windowing Toolkit (AWT)
Teaching Hours - 8, Total Marks - 12 (R - 2, U - 4, A - 6)
GridBagConstraints.BELOW_BASELINE_
GridBagConstraints.BELOW_BASELINE
LEADING
GridBagConstraints.
BELOW_BASELINE_TRAILING
The horizontal position can be either centered, against the leading edge (LEADING), or
against the trailing edge (TRAILING).
The weightx and weighty fields are both quite important and quite confusing at first glance.
In general, their values determine how much of the extra space within a container is allocated to each
row and column. By default, both these values are zero. When all values within a row or a column
are zero, extra space is distributed evenly between the edges of the window. By increasing the
weight, you increase that row or column’s allocation of space proportional to the other rows or
columns. The best way to understand how these values work is to experiment with them a bit.
The gridwidth variable lets you specify the width of a cell in terms of cell units. The default
is 1. To specify that a component use the remaining space in a row, use
GridBagConstraints.REMAINDER. To specify that a component use the next-to-last cell
in a row, use GridBagConstraints.RELATIVE. The gridheight constraint works the same
way, but in the vertical direction.
You can specify a padding value that will be used to increase the minimum size of a
cell. To pad horizontally, assign a value to ipadx. To pad vertically, assign a value to ipady.
// Use GridBagLayout.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="GridBagDemo" width=250 height=200> </applet>
*/
public class GridBagDemo extends Applet implements ItemListener {
String msg = "";
Checkbox windows, android, solaris, mac;
public void init() {
GridBagLayout gbag = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gbag);
// Define check boxes.
windows = new Checkbox("Windows ", null, true);
android = new Checkbox("Android");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
// Define the grid bag.
// Use default row weight of 0 for first row.
gbc.weightx = 1.0; // use a column weight of 1
gbc.ipadx = 200; // pad by 200 units
gbc.insets = new Insets(4, 4, 0, 0); // inset slightly from top left
gbc.anchor = GridBagConstraints.NORTHEAST;
gbc.gridwidth = GridBagConstraints.RELATIVE;
gbag.setConstraints(windows, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbag.setConstraints(android, gbc);
// Give second row a weight of 1.
gbc.weighty = 1.0;
gbc.gridwidth = GridBagConstraints.RELATIVE;
gbag.setConstraints(solaris, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbag.setConstraints(mac, gbc);
// Add the components.
add(windows);
add(android);
add(solaris);
add(mac);
// Register to receive item events.
windows.addItemListener(this);
android.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: " + windows.getState();
g.drawString(msg, 6, 100);
msg = " Android: " + android.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac: " + mac.getState();
g.drawString(msg, 6, 160);
}
}
You can disable or enable a menu item by using the setEnabled( ) method. Its form is
shown here:
36 | P a g e Mr. Satish S. Ambulge (HOD, CO Dept, VAPM, Almala
Adv. Java Programming (22517): 1- Abstract Windowing Toolkit (AWT)
Teaching Hours - 8, Total Marks - 12 (R - 2, U - 4, A - 6)
You can determine an item’s status by calling isEnabled( ). This method is shown here:
boolean isEnabled( )
isEnabled( ) returns true if the menu item on which it is called is enabled. Otherwise, it
returns false.
You can change the name of a menu item by calling setLabel( ). You can retrieve the
current name by using getLabel( ). These methods are as follows:
void setLabel(String newName)
String getLabel( )
Here, newName becomes the new name of the invoking menu item. getLabel( ) returns the
current name.
You can create a checkable menu item by using a subclass of MenuItem called
CheckboxMenuItem. It has these constructors:
CheckboxMenuItem( ) throws HeadlessException
CheckboxMenuItem(String itemName) throws HeadlessException
CheckboxMenuItem(String itemName, boolean on) throws HeadlessException
Here, itemName is the name shown in the menu. Checkable items operate as toggles.
Each time one is selected, its state changes.
In the first two forms, the checkable entry is unchecked. In the third form, if on is true, the
checkable entry is initially checked. Otherwise, it is cleared.
You can obtain the status of a checkable item by calling getState( ). You can set it to a
known state by using setState( ). These methods are shown here:
boolean getState( )
void setState(boolean checked)
If the item is checked, getState( ) returns true. Otherwise, it returns false. To check an
item, pass true to setState( ). To clear an item, pass false.
Once you have created a menu item, you must add the item to a Menu object by using
add( ), which has the following general form:
MenuItem add(MenuItem item)
Here, item is the item being added. Items are added to a menu in the order in which the
calls to add( ) take place. The item is returned.
Once you have added all items to a Menu object, you can add that object to the menu
bar by using this version of add( ) defined by MenuBar:
Menu add(Menu menu)
Here, menu is the menu being added. The menu is returned.
By default, the action command string is the name of the menu item. However, you can
specify a different action command string by calling setActionCommand( ) on the menu
item. Each time a check box menu item is checked or unchecked, an ItemEvent object is
generated. Thus, you must implement the ActionListener and/or ItemListener interfaces
in order to handle these menu events.
The getItem( ) method of ItemEvent returns a reference to the item that generated this
event. The general form of this method is shown here:
Object getItem( )
// Illustrate menus.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MenuDemo" width=250 height=250> </applet>
*/
// Create a subclass of Frame.
class MenuFrame extends Frame {
String msg = "";
CheckboxMenuItem debug, test;
MenuFrame(String title) {
super(title);
// create menu bar and add it to frame
MenuBar mbar = new MenuBar();
setMenuBar(mbar);
// create the menu items
Menu file = new Menu("File");
MenuItem item1, item2, item3, item4, item5;
file.add(item1 = new MenuItem("New..."));
file.add(item2 = new MenuItem("Open..."));
file.add(item3 = new MenuItem("Close"));
file.add(item4 = new MenuItem("-"));
file.add(item5 = new MenuItem("Quit..."));
mbar.add(file);
Menu edit = new Menu("Edit");
MenuItem item6, item7, item8, item9;
edit.add(item6 = new MenuItem("Cut"));
edit.add(item7 = new MenuItem("Copy"));
edit.add(item8 = new MenuItem("Paste"));
edit.add(item9 = new MenuItem("-"));
Menu sub = new Menu("Special");
MenuItem item10, item11, item12;
sub.add(item10 = new MenuItem("First"));
sub.add(item11 = new MenuItem("Second"));
sub.add(item12 = new MenuItem("Third"));
edit.add(sub);
// these are checkable menu items
debug = new CheckboxMenuItem("Debug");
edit.add(debug);
test = new CheckboxMenuItem("Testing");
edit.add(test);
mbar.add(edit);
// create an object to handle action and item events
MyMenuHandler handler = new MyMenuHandler(this);
// register it to receive those events
item1.addActionListener(handler);
item2.addActionListener(handler);
item3.addActionListener(handler);
item4.addActionListener(handler);
item5.addActionListener(handler);
item6.addActionListener(handler);
item7.addActionListener(handler);
item8.addActionListener(handler);
item9.addActionListener(handler);
item10.addActionListener(handler);
item11.addActionListener(handler);
item12.addActionListener(handler);
debug.addItemListener(handler);
test.addItemListener(handler);
// create an object to handle window events
MyWindowAdapter adapter = new MyWindowAdapter(this);
// register it to receive those events
addWindowListener(adapter);
}
public void paint(Graphics g) {
g.drawString(msg, 10, 200);
if(debug.getState())
g.drawString("Debug is on.", 10, 220);
else
g.drawString("Debug is off.", 10, 220);
if(test.getState())
g.drawString("Testing is on.", 10, 240);
else
g.drawString("Testing is off.", 10, 240);
}
}
class MyWindowAdapter extends WindowAdapter {
MenuFrame menuFrame;
public MyWindowAdapter(MenuFrame menuFrame) {
this.menuFrame = menuFrame;
}
public void windowClosing(WindowEvent we) {
menuFrame.setVisible(false);
}
}
class MyMenuHandler implements ActionListener, ItemListener {
MenuFrame menuFrame;
public MyMenuHandler(MenuFrame menuFrame) {
this.menuFrame = menuFrame;
}
// Handle action events.
public void actionPerformed(ActionEvent ae) {
String msg = "You selected ";
String arg = ae.getActionCommand();
if(arg.equals("New..."))
msg += "New.";
else if(arg.equals("Open..."))
msg += "Open.";
else if(arg.equals("Close"))
msg += "Close.";
else if(arg.equals("Quit..."))
msg += "Quit.";
else if(arg.equals("Edit"))
msg += "Edit.";
else if(arg.equals("Cut"))
msg += "Cut.";
else if(arg.equals("Copy"))
msg += "Copy.";
else if(arg.equals("Paste"))
msg += "Paste.";
else if(arg.equals("First"))
msg += "First.";
else if(arg.equals("Second"))
msg += "Second.";
else if(arg.equals("Third"))
msg += "Third.";
else if(arg.equals("Debug"))
msg += "Debug.";
else if(arg.equals("Testing"))
msg += "Testing.";
menuFrame.msg = msg;
menuFrame.repaint();
}
// Handle item events.
public void itemStateChanged(ItemEvent ie) {
menuFrame.repaint();
}
}
// Create frame window.
public class MenuDemo extends Applet {
Frame f;
public void init() {
f = new MenuFrame("Menu Demo");
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
setSize(new Dimension(width, height));
f.setSize(width, height);
f.setVisible(true);
}
public void start() {
f.setVisible(true);
}
public void stop() {
f.setVisible(false);
}
}
Dialog Boxes
Dialog boxes are primarily used to obtain user input and are often child windows of a
top-level window. Dialog boxes don’t have menu bars, but in other respects, they function like frame
windows.
Dialog boxes may be modal or modeless.
When a modal dialog box is active, all input is directed to it until it is closed. This means that
you cannot access other parts of your program until you have closed the dialog box.
When a modeless dialog box is active, input focus can be directed to another window in your
program. Thus, otherparts of your program remain active and accessible. Dialog boxes are of type
Dialog. Two commonly used constructors are shown here:
Dialog(Frame parentWindow, boolean mode)
Dialog(Frame parentWindow, String title, boolean mode)
Here, parentWindow is the owner of the dialog box. If mode is true, the dialog box is modal.
Otherwise, it is modeless. The title of the dialog box can be passed in title.
Notice that when the dialog box is closed, dispose( ) is called. This method is defined by
Window, and it frees all system resources associated with the dialog box window.
import java.awt.*;
import java.awt.event.*;
frame1.setLayout(new FlowLayout());
Button button = new Button("Application modal dialog");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Dialog dialog = new Dialog(frame1, "Application-Modal Dialog",
Dialog.ModalityType.APPLICATION_MODAL);
dialog.setBounds(200, 150, 200, 150);
dialog.setVisible(true);
}
});
frame1.add(button);
frame1.setBounds(100, 100, 200, 150);
frame1.setVisible(true);
Frame frame2 = new Frame("Frame 2");
frame2.setBounds(500, 100, 200, 150);
frame2.setVisible(true);
frame2.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
FileDialog
To create a file dialog box, instantiate an object of type FileDialog. This causes a file
dialog box to be displayed.Usually, this is the standard file dialog box provided by the operating
system. Here are three FileDialog constructors:
FileDialog(Frame parent)
FileDialog(Frame parent, String boxName)
FileDialog(Frame parent, String boxName, int how)
Here, parent is the owner of the dialog box. The boxName parameter specifies the
name displayed in the box’s title bar. If boxName is omitted, the title of the dialog box
is empty. If how is FileDialog.LOAD, then the box is selecting a file for reading. If how is
FileDialog.SAVE, the box is selecting a file for writing. If how is omitted, the box is selecting
a file for reading.
FileDialog provides methods that allow you to determine the name of the file and its
path as selected by the user. Here are two examples:
String getDirectory( )
String getFile( )
These methods return the directory and the filename, respectively.
// Demonstrate File Dialog box.This is an application, not an applet.
import java.awt.*;
import java.awt.event.*;
// Create a subclass of Frame.
class SampleFrame extends Frame {
SampleFrame(String title) {
super(title);
// remove the window when closed
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}
// Demonstrate FileDialog.
class FileDialogDemo {
public static void main(String args[]) {
// create a frame that owns the dialog
Frame f = new SampleFrame("File Dialog Demo");
f.setVisible(true);
f.setSize(100, 100);
FileDialog fd = new FileDialog(f, "File Dialog");
fd.setVisible(true);
}
}