1
Lecture 6Lecture 6
Using AWT controls, Layout Managers, and
Menus
2
IntroductionIntroduction
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
3
Control fundamentalsControl 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
4
Adding and removing controlsAdding 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
5
LabelsLabels 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)
6
ButtonsButtons 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
7
8
Buttons (contd.)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
9
Check BoxesCheck 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
10
Check Boxes (contd.)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
11
Check Box GroupCheck 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
12
Choice ControlsChoice 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 objectvoid 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()
13
Choice Controls (contd.)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
14
ListsLists List class provides a compact, multiple-choice,
scrolling selection list List object can be constructed to show any number
of choices in the visible windowList() //allow one item to be selected
List(int numRows) //specifies number of rowsList(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
15
Lists (contd.)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
16
Lists (contd.)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
17
Scroll BarsScroll 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)
18
Scroll Bars (contd.)Scroll Bars (contd.) Scroll bars are encapsulated by the class Scrollbar
Scrollbar() //create vertical scroll barScrollbar(int style) //style is Scrollbar.VERTICAL or
Scrollbar.HORIZONTALScrollbar(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)
19
Scroll Bars (contd.)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)
20
Scroll Bars (contd.)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
21
TextField/Edit controlTextField/Edit control TextField is a single-line text-entry and a subclass of
TextComponent Textfield defines the following constructors:
TextField() //default text fieldTextField(int numChars) //wide specifiedTextField(String str) //default string in the text fieldTextField(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)
22
TextField/Edit control (contd.)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
23
TextAreaTextArea
It is a multiline editorTextArea()TextArea(int numLines, int numChars) //height specifiedTextArea(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
24
TextArea (contd.)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
25
Understanding Layout ManagersUnderstanding 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
26
Layout Managers (contd.)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
27
Layout Managers (contd.)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
28
FlowLayoutFlowLayout
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
29
Border LayoutBorder 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 centerBorderLayout() //default order layout
BorderLayout(int horz,int vert) //allows to specify horizontal and vertical space between components
Components are added byvoid add(Component compObj, Object region);
Example: BorderLayoutDemo
30
Using InsetsUsing 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
31
Grid LayoutGrid Layout
It lays out components in a two-dimensional gridGridLayout() //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
32
Menu Bars and MenusMenu 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 objectsMenuBar()
Menu object can be created by Menu()Menu(String optionName)
33
Menu Bars and Menus (contd.)Menu Bars and Menus (contd.) Each Menu object contains a list of MenuItem objects,
that can be selected by user. Its constructors areMenuItem()
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()
34
Menu Bars and Menus (contd.)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
35
Dialog BoxesDialog 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
36
File dialogFile dialog
It is used to specify a fileFileDialog(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
Top Related