|
Section 8 : The java.awt Package
Write
code using component, container, and LayoutManager
classes of the java.awt package to present a GUI with
specified appearance and resize behavior, and
distinguish the responsibilities of layout managers
from those of containers.
Components
Java’s
components are implemented by many subclasses of the
java.awt.Component and java.awt.MenuComponent
superclasses. There are several methods that are
implemented by all the visual and container
components, by virtue of inheritance from Component.
The menu components extend from MenuComponent, so they
do not inherit the same super class functionality.
getSize()
Returns Dimension, which
has public data members width and height.
void setBackground() and
setForeground()
if you do not explicitly
set a component’s foreground and background colors,
the component uses the colors of its immediate
container. Some components on some platforms resist
having their colors changed.
void setFont(Font f)
if you do not explicitly
set a component’s font, the component uses the font of
its container.
void setEnabled(boolean flag)
if the argument is true,
then the component has its normal appearance,
otherwise the component is grayed out and does not
respond to user inputs.
setSize(int x,
int y), setSize(Dimension d), setBounds(x, y,
width, height), setBounds(Rectangle r)
the size and position
that you attempt to give a component is overruled by a
layout manager. In fact, these two methods exist
mostly for the use of layout managers. The major
exception to this rule is the Frame class, which is
not under the thumbs of a layout manager and is
perfectly willing to have you set its size or bounds.
void setVisible(boolean flag)
The visible components
Button
(generates
ActionEvent)
Its constructors are:
-
Button()
-
Button(String label)
Some of the methods are:
-
String
getActionCommand()
-
void
setActionCommand()
-
String
getLabel()
-
void
setLabel()
-
EventListener[] getListeners(Class listenerType)
-
void
processActionEvent(ActionEvent ae)
-
void
processEvent(AWTEvent e)
-
void
addActionListener(ActionListener l)
-
void
removeActionListener(ActionListener l)
Canvas (generates
Mouse, MouseMotion, and Key events)
Its constructors are:
A canvas is a component
that has no default appearance or behavior. It
represents a blank rectangular area of the screen onto
which the application can draw or from which the
application can trap input events from the user. You
can subclass Canvas to create custom drawing regions,
work areas, components and so on.
The default size of a
canvas is uselessly small. One way to deal with this
problem is to use a layout manager that will
resize the canvas. Another way is to call
setSize() on the canvas yourself. Canvases are a rare
case where this will actually work.
An application must
subclass Canvas to get useful functionality such as
creating a custom component. The paint() method must
be overridden in order to perform custom graphics on
the canvas.
Checkbox (generates Item event)
A checkbox is a two
state button: true(checked) and false(unchecked).
Its constructors are:
-
Checkbox()
-
Checkbox(String label)
-
Checkbox(String label, boolean
state)
-
Checkbox(String label, boolean
state, CheckboxGroup group)
-
Checkbox(String label, CheckboxGroup group,
boolean state)
The default state is
false. If you pass null for group in 4th or
5th constructor, it will mean that the
checkbox does not belong to any group.
Unlike many window
systems which implement radio groups as components in
their own right, in Java CheckboxGroup class is not a
component. It is simply a non-visible class that
organizes checkboxes. This means that Java imposes no
restrictions on the spatial relationships among
members of a checkbox group.
Some of its methods are:
-
CheckboxGroup getCheckboxGroup();
Returns null if there is none.
-
String
getLabel();
-
void
setLabel(String s);
-
EventListener[] getListeners(Class listenerType);
-
Object
[] getSelectedObject();
-
void
setCheckboxGroup(CheckboxGroup g); if this
checkbox is already in a different group, it is
first taken out of that group.
Choice
(generates Item event)
A choice is a pull down
list or pop-up menu of choices. The current choice is
displayed as the title of the pop-up menu (choice). It
provides only the no-args constructor. To create a
choice, first call the constructor, and then populate
the choice by repeatedly calling addItem(String s).
Some of its methods are:
-
void
add(String item)
-
void
addItem(String item)
-
String
getItem(int index)
-
int getItemCount()
-
int getSelectedIndex()
-
String
getSelectedItem()
-
Object
[] getSelectedObjects()
-
void
insert(String item, int
index)
-
void
remove(int position)
-
void
remove(String item)
-
void
removeAll()
-
void
select(int index)
-
void
select(String item)
FileDialog
This class extends
Dialog. It represents a file open or file save dialog.
The appearance of these dialogs vary from platform to
platform. A file dialog is modal. This means that
input from the dialog’s parent frame will be directed
exclusively to the dialog, as long as the dialog
remains visible on the screen. The dialog is
automatically removed when the user specifies a file
or clicks the Cancel buttons.
Its constructors are:
-
FileDialog(Frame parent)
-
FileDialog(Frame parent, String title)
-
FileDialog(Frame parent, String title,
int mode)
First and second
constructors are for loading a file. If the value of
mode in the third constructor is FileDialog.LOAD, then
the file dialog is finding a file to read. If the
value is FileDialog.SAVE, the file dialog is finding a
place to write a file.
Label
Labels do not respond to
user inputs, and they do not send any events. The
default alignment for the labels is to the left.
List
(on selection
ItemEvent, on double-clicking ActionEvent is
generated)
A list is a collection
of text items, arranged vertically. If a list contains
more items than it can display it acquires a vertical
scrollbar. The constructors are:
Some of its methods are:
-
void
add(String text)
-
void
add(String text, int
index)
-
String
getItem(int index)
-
int getItemCount()
-
int getRows()
-
int getSelectedIndex()
-
int []
getSelectedIndexes()
-
String
getSelectedItem()
-
String []
getSelectedItems()
-
void
remove(int position)
-
void
remove(String item)
-
void
removeAll()
-
void
replaceItem(String newValue,
int index)
-
void
select(int index)
-
void
setMultipleMode(boolean
flag)
ScrollPane
(extends Container. Generates Mouse and MouseMotion
events)
A scrollPane can contain
a single component, which may be taller or wider than
the scroll pane itself ( then it acquires scrollbars).
The initial size of this container is 100x100, but can
be reset using setSize(). There are two constructors:
scrollbarPolicy should
be one of the following:
-
ScrollPane.SCROLLBARS_AS_NEEDED
-
ScrollPane.SCROLLBARS_ALWAYS
-
ScrollPane.SCROLLBARS_NEVER
Scrollbar
(Adjustment event)
There are three
constructors:
-
Scrollbar()
-
Scrollbar(int
orientation)
-
Scrollbar(int
orientation, int
initial value, int
sliderSize, int
minValue, int maxValue)
Orientation can be
one of the following:
-
Scrollbar.HORIZONTAL
-
Scrollbar.VERTICAL
The defaults are:
Orientation – vertical,
unit increment – 1, block increment – 10, value – 0
which controls the location of the scrollbar bubble,
minimum – 0, maximum – 100.
The piece of the scroll
bar that slides is called slider. The slider size
parameter controls the size of the slider, but not in
pixel units. The units of slider size parameter are
the units defined by the spread between the minimum
and maximum value of the scroll bar.
TextField and
TextArea (TextEvents, ActionEvents on receipt of
Enter keystroke)
Both classes extend from
TextComponent, which extends Component. Constructors
are:
TextField ()
TextField (int nColumns)
TextField (String text)
TextField (String text,
int nColumns)
TextArea ()
TextArea (int rows,
int columns)
TextArea (String text)
TextArea (String text,
int rows,
int columns)
TextArea (String text,
int rows,
int columns,
int scrollBarPolicy)
The last parameter
should be one of the following:
TextArea.SCROLLBARS_BOTH
TextArea.SCROLLBARS_NONE
TextArea.SCROLLBARS_HORIZONTAL_ONLY
TextArea.SCROLLBARS_VERTICAL_ONLY
For both classes , there
are some surprising issues to the number of columns
parameter. First, vColumns is a measure of width in
terms of columns if text, as rendered in a particular
font. Next, there is the problem of proportional font.
For a fixed width font, the column width is obvious.
For a proportional font, the column width is average
of all the font’s character widths. Some of the space
is taken up by leading and inter-character white
space. So, five column wide component may not show
five characters.
A final issue arises
when a user types beyond the rightmost column. The
visible text scrolls to the left. The insertion point
remains in place, at the rightmost column.
Text areas support
scroll bars, text fields can be scrolled by using the
arrow keys.
The common methods
inherited by these from TextComponent:
Additional methods for
text field are:
// If the character is 0, user input is echoed
unchanged.
Additional methods for
text area are:
The container components
Applet
Applets, by virtue of
inheriting from Component, have setSize() and
setBounds() methods. They only exist in browsers.
Changing the size of an applet is permitted or
forbidden by the browser, and during the development
cycle you cannot know the browser which will be
running the applet. Appletviewer allows resizing of
applets. It is common for an applet to have a
temporary setSize() call in its init() method, because
this provides an easy way to play with different
sizes. If you use this technique, you should delete
the setSize() call before final delivery, and set size
in your html pages.
Frame
A frame is an
independent, top level window with a title bar and a
border, decorated by the underlying window system and
capable of being moved around on the screen
independent of other GUI windows. Its size includes
the size of the window. The dimensions of the border
can be obtained by getInsets() method, but since these
dimensions are platform dependent, a valid insets
value cannot be obtained until the frame is made
displayable by calling either pack() or show().
Any application that
requires a GUI must use one or more frames to contain
desired components.
The constructors are:
-
Frame()
-
Frame(String title)
When a frame is
constructed it has no size and is not displayed on the
screen. To give a size, call one of inherited methods
setSize() or setBounds(). To display it, call
setVisible(true). To remove an unwarranted frame from
the screen, call setVisible(false). This does not
destroy the frame or damage it; you can display it
again by setVisible(true).
When you are finished
with a frame, you need to recycle its non-memory
resources, which are system dependent; suffice it to
say that it takes a lot to connect a Java GUI to an
underlying window system. To release the non-memory
resources of a frame, just call its dispose() method.
When a frame is
displayed in an applet, it normally carries a warning.
The rationale behind it is that the applet might have
been loaded from the internet, so any sensitive
information entered into the frame’s components might
possibly be transmitted to parties of dubious moral
fiber.
Some of the methods are:
-
Image
getIconImage()
-
void
setIconImage(Image image)
-
MenuBar
getMenuBar()
-
String
getTitle()
-
boolean isResizable()
-
void
setResizable(boolean
flag)
-
void
setMenuBar(MenuBar m)
-
void
setTitle(String s)
If image parameter is
null, then image is set to platform dependent default
image.
Panel
Applets and frames serve
as top-level or outermost GUI components. Panels
provide an intermediate level of spatial organization
for GUIs. You are free to add all the components of a
GUI directly into an applet or a frame, but you can
provide additional levels of grouping by adding
components to panels and adding panels to a top level
applet or frame.
Constructors are:
-
Panel()
-
Panel(LayoutManager)
Dialog
It is a pop up window
with a title bar and a border, that accepts user
input. It must have a frame or another dialog defined
as its owner when it is constructed. When owner is
hidden or minimized, the dialog is automatically
hidden and is visible again with the owner. Dialogs
may optionally be made modal or modeless(default). A
modal dialog is one which blocks input to all other
top level windows in the app context, except for the
windows created with the dialog as their owner. The
Dialog class is the superclass of the FileDialog
class. The default layout manager for this class is
BorderLayout.
Constructors:
-
Dialog(Dialog owner)
-
Dialog(Dialog owner, String title)
-
Dialog(Dialog owner, String title,
boolean modal)
-
Dialog(Frame owner)
-
Dialog(Frame owner, String title)
-
Dialog(Frame owner, boolean
modal)
-
Dialog(Frame owner, String title,
boolean modal)
All the seven
constructors construct an initially invisible Dialog.
Methods are:
Note : pack() defined in
Window causes the window to be sized to fit the
preferred size and layout of its subcomponents. If the
window and / or its owner are not yet displayable,
both are made displayable before calculating the
preferred size. The window will be validated after the
preferred size is calculated.
The Menu
components
There are two types pop
up and pull down. Pull down menus are accessed via a
menu bar, which may contain multiple menus. Menu bars
may appear only in frames.
To create a frame with a
menu bar containing a pull down menu:
-
Create a
menu bar and attach it to frame.
-
Create
and populate the menu.
-
Attach
the menu to the menu bar.
To create a menu bar,
instantiate MenuBar class. To attach it to frame, pass
it into the frame’s setMenuBar().
To create a menu,
instantiate Menu class. The most common constructor
takes a string that is the menu’s label. There are
four kinds of elements that can be mixed and matched
to populate a menu:
MenuItem(String text)
where text is the label of the menu item.
A menu item is very much
like a button that happens to live in a menu. Like
buttons, menu items generates action events.
-
Checkbox
MenuItems
-
A
checkbox menu item looks like a menu item with a
checkbox to the left of its label. When a checkbox
menu item is selected, the checkbox changes its
state. The basic constructor is
CheckboxMenuItem (String label);. You can read
and set an item’s state by calling getState() and
setState(). These generate ItemEvents.
-
Separators
-
Menus
After a menu is fully
populated, you attach it to a menu bar by calling menu
bar’s add() method. If you want the menu to appear in
the Help menu position to the right of all other
menus, call instead setHelpMenu().
The hierarchy of
java.awt package is like this:
Object
-
EventObject
-
AWTEvent
-
ActionEvent
-
AdjustmentEvent
-
ComponentEvent
-
ContainerEvent
-
FocusEvent
-
InputEvent
-
PaintEvent
-
WindowEvent
-
ItemEvent
-
TextEvent
section8-1-1 | section8-1-2 | section8-1-3 | section8-2
Sections :
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11
If you wish to download the complete notes
(around 100 pages - pdf or doc file) for a small price, click here. |