Lecture slider
Document Sample


Lecture 6
Using AWT controls,
Layout Managers, and
Menus
1
Introduction
Controls are components that allow a user
to interact with your application in various
ways
A layout manager automatically positions
components within a container
Frame window can include a standard-style
menu bar. Each entry in a menu bar
activates a drop-down menu of options
from which user can choose
2
Control fundamentals
The Awt support the following types of
controls:
Labels
Push buttons
Check boxes
Lists
Scroll bars
Text editing
These controls are subclass of components
3
Adding and removing controls
To include a control in a window, we have to
First create an instance of the desired control
Then add it to a window by calling add() (defined by
Container)
i.e. Component add (Component compObj)
Once a control has been added, it will automatically
be visible whenever its parent window is displayed
We can remove control from a window by calling
void remove(Component obj)
We can remove all controls by calling removeAll()
Except labels (passive control), all controls generate
events when they are accessed by the user
4
Labels
A label is an object of type Label
It contains a String which it displays
Label defines the following constructors:
Label() //create blank label
Label (String str) //create label with the string in left-justified
Label (String str, int how) //create label with the string using
alignment specified by how
The value of how must be one of the three constants:
Label.LEFT, Label.Right or Label.CENTER
We can set or change the text by setText(String str) method
Current label can be obtained by String getText() method
Methods are also available like setAlignment() or
getAlignment (See LabelDemo for example)
5
Buttons
Push buttons are objects of type Button
Button()
Button(String str) // str will label
Label can be set by setLabel(String str) and label
can be retrieved by String getLabel()
Each time a button is pressed, an action event is
generated, which is sent to registered listeners
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 an argument
6
7
Buttons (contd.)
Which button has been pushed can be identified
by a reference to the button that generated the
event or by a reference to the label of the button
The reference to the button can be obtained by
getSource() method of ActionEvent object
The label can be obtained by calling
getActionCommand() method of ActionEvent
object
Button references can be stored into an array of
buttons
Example: ButtonDemo and ButtonList
8
Check Boxes
A control that is used to turn an option on or off
Check box can be used individually or as part of a
group
Check boxes are objects of the Checkbox class
Checkbox() //unchecked checkbox with blank label
Checkbox(String str) // unchecked but have a label
Checkbox(String str, boolean on) //can be checked and have a label
Checkbox(String str, boolean on, CheckboxGroup cbGroup)
Checkbox(String str, CheckboxGroup cbGroup, boolean on) //can be
included in a group if cbGroup is not null
9
Check Boxes (contd.)
Current state of a check box can be set by
setState(boolean on) or retreived by boolean
getState()
Each time a check box is selected or deselected,
an item event is generated
Each listener implements the ItemListener
interface that defines itemStateChanged() method
An ItemEvent object is supplied as the argument
to this method, which contain information about
the event
Example: CheckboxDemo
10
Check Box Group
Mutually exclusive check boxes in which one and only
one check box in the group can be checked at a time
Also called radio buttons
First define a check box group by creating an object of
type CheckboxGroup
Then mention the group name in the check box
constructor
Which check box is selected can be determined by
Checkbox getSelectedCheckbox()
Any chekbox can be set by
setSelectedCheckbox(Checkbox which)
Example: CBGroup
11
Choice Controls
Choice class is used to create a pop-up list of items
from which user may choose
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
void addItem (String name)
void add(String name)
Which item is selected can be can be determined by
String getSelectedItem() or int getSelectedIndex()
Number of items can be determined by int
getItemCount()
12
Choice Controls (contd.)
Any item can be set by select (int index) or
select (String name)
Any item name can be found by index by
calling String getItem(int index)
Choice control creates ItemEvent object
Listeners implement ItemListener
interface, that defines itemStateChanged()
method
Example: ChoiceDemo
13
Lists
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
List() //allow one item to be selected
List(int numRows) //specifies number of rows
List(int numRows, boolean multipleSelect) //multiple item
can be selected
To add a slection to the list, call add(String name)
or add(String name, int index)
Indexing begin at 0and –1 indicates end of the
list
14
Lists (contd.)
Which item is/are currently selected can be
determined by
String getSelectedItem(),
int getSelectedIndex()
Or String[ ] getSelectedItems(),
int[ ] getSelectedIndexes
Similar methods available like select(), getItem(),
getItemCount() etc
For double clicking an item, list control produce
ActionEvent type object
Implement ActionListener interface, which has
actionPerformed() method
Object’s getActionCommand() is used to track which
item is double-clicked 15
Lists (contd.)
For single clicking an item, list control
produce
ItemEvent type object
Implement ItemListener interface, which has
itemStateChanged() method
Object’s getStateChanged() is used to track
whether any item is selected or deselected
Object’s getItemSelectable() is used to track
which item triggered this event
Example: Listdemo
16
Scroll Bars
This control is used to select continuous values
between a specified minimum and maximum
It may be oriented horizontally or vertically
Each end has an arrow, click on it move current
value of the scroll bar one unit in the direction
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
Slider can be dragged to a new position
By mouse click, slider can jump by more than 1
(like page up and page down)
17
Scroll Bars (contd.)
Scroll bars are encapsulated by the class Scrollbar
Scrollbar() //create vertical scroll bar
Scrollbar(int style) //style is Scrollbar.VERTICAL or
Scrollbar.HORIZONTAL
Scrollbar(int style, int initialValue, int thumbSize, int min,
int max) //specifies initial position, height of thumb,
minimum and maximum position
If Scroll bar is created by one of the first two
constructors, then its other parameters must be set
by
setValues(int initialValue, int thumbSize, int min, int max)
18
Scroll Bars (contd.)
getValue() is used to obtain the current value of
the scroll bar. setValue(int newValue) is used to
set current value
Minumim and maximum values can be obtained
by getMinimum() and getMaximum()
By default increment or decrement is 1. It can be
changed by setUnitIncrement(int newIncr)
By default, page-up and page-down increments
are 10. It can be changed by
setBlockIncrement(int newIncr)
19
Scroll Bars (contd.)
Interaction with a scroll bar creates
AdjustmentEvent object
Its getAdjustmentType() is used to
determine type of adjustment (i.e.
BLOCK_DECREMENT, TRACK,
UNIT_INCREMENT etc)
To handle this event, we need to implement
AdjustmentListener interface
Example: SBDemo
20
TextField/Edit control
TextField is a single-line text-entry and a subclass of
TextComponent
Textfield defines the following constructors:
TextField() //default text field
TextField(int numChars) //wide specified
TextField(String str) //default string in the text field
TextField(String str, int numChars)
Method to obtain the current string is
String getText()
To set a text, call setText(String str)
A portion of the text under selection can be obtained
by String getSelectedText()
To select a portion of a text, call select(int startIndex,int
endIndex) 21
TextField/Edit control (contd.)
Editibility of a text field can be set by
setEditable(boolean canEdit)
Text can be modified or not is checked by
boolean isEditable()
We can disable the echoing of the characters and
display another character by setEchoChar(char
ch)
Similar methods are boolean echoCharIsSet() and
char getEchoChar()
TextField generates ActionEvent object
Example: TextFieldDemo
22
TextArea
It is a multiline editor
TextArea()
TextArea(int numLines, int numChars) //height specified
TextArea(String str)
TextArea(String str,int numLines, int numChars)
TextArea(String str,int numLines,int numChars,int
sBars) //specify scroll bar to have with it
TextArea is a subclass of TextComponent, so it
supports the getText(), setText(),
getSelectedText(), select(), isEditable(),
setEditable() etc. methods
23
TextArea (contd.)
TextArea adds the following methods
append(String str) //appends str at the end of current text
insert(String str, int index) //insert str at specified index
replaceRange(String str, int startIndex, int endIndex)
TextArea generates got-focus and lost-
focus events
Example: TextAreaDemo
24
Understanding Layout Managers
Layout manager automatically arranges controls
within a window by using some types of
algorithm
Until now, we have used he default layout
manager
Placing controls in a window by hand is not
feasible, because:
It is very tedious
Sometimes the width and height information is not
yet available
25
Layout Managers (contd.)
Each container object has a layout manager
associated with it.
A layout manager is an instance of any class that
implements the LayoutManager interface
The layout manager is set by
setLayout(LayoutManager layoutObj)
layoutObj is a reference to the desired layout
manager
If layoutObj is set null, we have to position
components manually
26
Layout Managers (contd.)
The layout manager is notified each time a
component is added to a container
Whenever a 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
The layout manager will honor these requests if at
all possible, maintaining the integrity of the
layout policy
27
FlowLayout
It is the default layout manager, similar to
how words flow in a text
FlowLayout() //centers components and leaves five pixels
between each component
FlowLayout(int how) //how can be FlowLayout.LEFT..etc
FlowLayout(int how, int horz, int vert) //specifies
horizontal and vertical spacing between components
Example: FlowLayoutDemo
28
Border Layout
It has 4 narrow, fixed-width components at
the edges and one large area in the center
4 sides are called north, south, east and
west, middle are is called center
BorderLayout() //default order layout
BorderLayout(int horz,int vert) //allows to specify
horizontal and vertical space between components
Components are added by
void add(Component compObj, Object region);
Example: BorderLayoutDemo
29
Using Insets
Allows to leave a small amount of space
between the container that holds our
components and the window that contains it
Insets(int top,int left,int bottom,int right)
Insets is created in the overridden
getInsets() method defined by Container
Example: InsetsDemo
30
Grid Layout
It lays out components in a two-dimensional
grid
GridLayout() //single column grid layout
GridLayout(int numRows, int numColumns)
GridLayout(int numRows,int numColumns,int horz,int vert)
If numRows=0, the column length is
unlimited. Also if numColumns=0, the row
length is unlimited
Example: GridLayoutDemo
31
Menu Bars and Menus
A menu bar displays a list of top-level menu
choices
Each choice is associated with a drop-down menu
Menu is implemented by the classes MenuBar,
Menu and MenuItem.
First create a Menu bar, that contains one or more
Menu objects
MenuBar()
Menu object can be created by
Menu()
Menu(String optionName)
32
Menu Bars and Menus (contd.)
Each Menu object contains a list of MenuItem
objects, that can be selected by user. Its constructors
are
MenuItem()
MenuItem (String itemName)
MenuItem (String itemName, MenuShortcut keyAcccel)
Since Menu is a subclass of MenuItem, hierarchy of
nested submenus can be created
A menu item can be enabled or disable by
setEnable() method
An items status can be determined by isEnabled()
The name of a menu item can be changed by
setLabel(); name can be retrieved by getLabel()
33
Menu Bars and Menus (contd.)
A checkable menu item can be created by
CheckboxMenuItem, a subclass of MenuItem
MenuItem can be added to a Menu by add()
Also menu is added to a ManuBar by add()
Menus only generate only ActionEvent when an
item of type MenuItem is selected (ItemEvent is
generated by CheckboxMenuItem)
getItem() method of ItemEvent returns a reference
to the item that generated this event
Eample: MenuDemo
34
Dialog Boxes
It holds a set of related controls and primarily
used to obtain user input
They are always a child window and don’t have
any menu bars
Dialog boxes can be modal (all input is directed
to it until it is closed, other part of the program
remains inactive) or modeless (input focus can be
directed to another window)
Dialog (Frame parentWindow, boolean mode)
Dialog (Frame parentWindow, String title, boolean mode)
When the dialog box is closed, dispose() is called,
which is defined by Window
Example: DialogDemo 35
File dialog
It is used to specify a file
FileDialog(Frame parent, String boxName) //parent is the
honour of the dialog box, boxName is the title of the box
FileDialog(Frame parent, String boxName,int how) // how =
FileDialog.LOAD for reading and FileDialog.SAVE for writing
FileDialog(Frame parent)
getDirectory() and getFile() is used to get
directory and file name
Example: FileDialogDemo
36
Get documents about "