Vous êtes sur la page 1sur 157

TOPICS

Control Fundamentals

Labels Using Buttons Applying Check Boxes CheckBox Group Choice Controls Using Lists Managing Scroll Bars Using a Text Field Using a TextArea Understanding Layout Managers , Menu Bars and Menus Dialog Boxes FileDialog Handling Events by Extending AWT Components.

Control Fundamentals
The AWT supports the following types of controls:

Adding and Removing Controls


To add a control to a window :

1. first create an instance of the desired control


2. then add it to a window by calling add( ) , which is defined by Container. Component add(Component compObj)
compObj An instance of the control that you want to add

A reference to compObj is returned.

Adding and Removing Controls


To remove a control , call remove( ). This method is also defined by Container

void remove(Component obj)


compObj A reference to the control that you want to remove

You can remove all controls by calling removeAll( )

Responding to Controls
In general, your program simply implements the appropriate interface and then registers an event listener for each control that you need to monitor.

HeadlessException
Generated by all constructors of the controls
Thrown when code that is dependent on a keyboard, display, or mouse is called in an environment that does not support a keyboard, display, or mouse. Added by java 1.4

Labels
A label is an object of type Label, and it contains a

string, which it displays. Label defines the following constructors:


1. Label( )
2. Label(String str) 3. Label(String str, int how)

1. The first version creates a blank label. 2. The second version creates a label that contains the

string specified by str.(left-justified.)


3. The third version creates a label that contains the string specified by str using the alignment specified by how

Labels
The value of how must be one of these three constants: 1. Label.LEFT, 2. Label.RIGHT, 3. Label.CENTER. Methods : void setText(String str) set or change the text in a label
String getText( ) obtain the current label
void setAlignment(int how) set the alignment of the string int getAlignment( ) obtain the current alignment

how must be one of the alignment constants shown above

The following example creates three labels and adds them to an applet:

Following is the window created by the LabelDemo applet

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. Constructors:
1. Button( ) creates an empty button

2. Button(String str) creates a button that contains str as a label. Methods :

1. void setLabel(String str) set the label


2. String getLabel( ) retrieve the label

Handling Buttons
Each time a button is pressed, an Action Event is generated. Each listener implements the ActionListener interface. This interface defines the actionPerformed( ) method, which is called when an event occurs. An ActionEvent object is supplied as the argument to this

method.
The label is obtained by calling getActionCommand() on ActionEvent Object (ActionEvent contains both a reference to the button that generated the
event and a reference to the string that is the label of the button)

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

Sample output

Handling Buttons
You can also determine which button has been pressed, by

comparing the object obtained from the getSource( ) method

To do this, you must keep a list of the objects when they are added.

Handling Buttons

Applying Check Boxes

Applying Check Boxes


A check box is a control that is used to turn an option on or off There is a label associated with each checkbox that describes

what option the box represents


Check boxes are objects of the Checkbox class.

Constructors:
1. Checkbox( ) 2. Checkbox(String str) 3. Checkbox(String str, boolean on) 4. Checkbox(String str, boolean on, CheckboxGroup cbGroup) 5. Checkbox(String str, CheckboxGroup cbGroup, boolean on)

Applying Check Boxes


1. The first form creates a check box whose label is initially blank. The state of the check box is unchecked 2. The second form creates a check box whose label is specified by str. The state of the check box is unchecked 3. The third form allows you to set the initial state of the

check box.
4. 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.

Applying Check Boxes Methods : 1. boolean getState( ) retrieve the current state of a

check box
2. void setState(boolean on) To set its state 3. String getLabel( ) obtain the current label associated with a check box 4. void setLabel(String str) To set the label if on is true, the box is checked. If it is false, the box is cleared.

Handling Check Boxes Each time a check box is selected or deselected, an item event is generated Your program must implement ItemListener Interface This interface defines the itemStateChanged( ) method

An ItemEvent object is supplied as the argument to this


method.

An ItemEvent object contains information about the


event

Handling Check Boxes


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.

Handling Check Boxes Sample output

CheckboxGroup

CheckboxGroup

(radio buttons)

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.

Check box groups are objects of type CheckboxGroup

Constructor :
CheckboxGroup() creates an empty group

Methods:
1. Checkbox getSelectedCheckbox( ) get status 2. void setSelectedCheckbox(Checkbox which) set a check box which the check box that you want to be selected

CheckboxGroup

(radio buttons)

First define the group to which they will belong and then specify that group when you construct the check boxes.

CheckboxGroup

(radio buttons)

Output generated by the CBGroup applet is shown

Choice Controls

Choice Controls

A Choice control is a form of menu.

The Choice class is used to create a pop-up list of items from

which the 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

Constructor (default):
Choice () creates an empty list.

Choice Controls
Methods :
1. void add(String name) add a selection to the list 2. String getSelectedItem( ) returns a string containing the name of the item 3. int getSelectedIndex( ) returns the index of the item 4. int getItemCount( ) obtain the number of items in the list 5. void select(int index) select an item with a zero-based integer index

6. void select(String name) select an item with a string


7. String getItem(int index) obtain the name associated with the item at the given index.

Handling Choice Lists


Each time a choice is selected, an item event is generated. Each listener implements the ItemListener interface

That interface defines the itemStateChanged( )


method

An ItemEvent object is supplied as the argument to


this method.

Handling Choice Lists


Here is an example that creates two Choice menus. One selects the operating system. The other selects the browser.

Handling Choice Lists


Sample output is shown

Using Lists

Using Lists
The List class provides a compact, multiple-choice, scrolling selection list

Constructors : 1. List( ) creates a List control that allows only one item to be selected at any one time. 2. List(int numRows) The value of numRows specifies the number of entries in the list that will always be visible.

3. List(int numRows, boolean multipleSelect) If


multipleSelect is true, then the user may select two or more items at a time.

Using Lists
Methods :

1. void add(String name) adds items to the end of


the list 2. void add(String name, int index) adds the item at the index specified by index 3. String getSelectedItem( ) returns a string containing the name of the item. 4. int getSelectedIndex( ) returns the index of the

item

Methods :
5. String[ ] getSelectedItems( ) returns an array containing the names of the currently selected items.

6. int[ ] getSelectedIndexes( ) returns an array


containing the indexes of the currently selected items. 7. int getItemCount( ) obtain the number of items in the list 8. void select(int index) set the currently selected item

9. String getItem(int index) obtain the name associated


with the item at the index

Handling Lists
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 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:

Managing Scroll Bars

Managing Scroll Bars


Scroll bars are used to select continuous values between a specified minimum and maximum. Scroll bars may be oriented horizontally or vertically 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. Scroll bars are encapsulated by the Scrollbar class

Managing Scroll Bars


Constructors
1. Scrollbar( )

creates a vertical scroll bar.

2. Scrollbar(int style) style specifies the orientation . style can be Scrollbar.VERTICAL Scrollbar.HORIZONTAL 3. Scrollbar(int style, int initialValue, int thumbSize, int min, int max) initialValue the initial value of the scroll bar
thumbSize The number of units represented by the height of the thumb min , max The minimum and maximum values for the scroll bar

Managing Scroll Bars


Methods :
1. void setValues(int initialValue, int thumbSize, int min, int max)

set its parameters


2. 3. 4. 5. int getValue( ) obtain the current value of the scroll bar void setValue(int newValue) set the current value int getMinimum( ) retrieve the minimum values int getMaximum( ) retrieve the maximum values

6.
7.

void setUnitIncrement(int newIncr) change the increment (default : 1)


void setBlockIncrement(int newIncr) page-up and page-down increments (default : 10)

Handling Scroll Bars


Interaction with a scroll bar, generates an Adjustment Event you need to implement the AdjustmentListener interface This interface defines adjustmentValueChanged() method which takes AdjustmentEvent object as the argument getAdjustmentType( ) of AdjustmentEvent can be used to determine the type of the adjustment.

Handling Scroll Bars


The types of adjustment events are as follows:

Handling Scroll Bars


The following example creates both a vertical and a horizontal scroll bar. 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.

Handling Scroll Bars

Handling Scroll Bars

Handling Scroll Bars

Handling Scroll Bars

Handling Scroll Bars


Sample output

Using a TextField

Using a TextField
The TextField class implements a single-line text-entry area, usually called an edit control.

TextField is a subclass of TextComponent

Constructors :
1. TextField( ) creates a default text field 2. TextField(int numChars) creates a text field that is numChars characters wide 3. TextField(String str) initializes the text field with the string 4. TextField(String str, int numChars) initializes a text field and sets its width

Using a TextField
Methods
1. String getText( ) obtain the curent string 2. void setText(String str) To set the text 3. String getSelectedText( ) select a portion of the text 4. void select(int startIndex, int endIndex) currently selected text

obtain the

Using a TextField
Methods
5. void setEditable(boolean canEdit) if canEdit is true, the

text may be changed. If it is false, the text cannot be altered


6. boolean isEditable( ) determine editability 7. void setEchoChar(char ch) disable the echoing of the characters 8. boolean echoCharIsSet( ) check a text field to see if it is in this mode 9. char getEchoChar( ) retrieve the echo character

Handling a TextField
Text Field generates Action Event when ENTER key is pressed.

Sample output

Using a TextArea

Using a TextArea
AWT includes a simple multiline editor called TextArea TextArea is a subclass of TextComponent

Constructors :
1. TextArea( )

2. TextArea(int numLines, int numChars)


3. TextArea(String str) 4. TextArea(String str, int numLines, int numChars)

5. TextArea(String str, int numLines, int numChars, int sBars)

Using a TextArea
Constructors : numLines specifies the height, in lines, numChars specifies its width, in characters. str Initial text sBars must be one of these values :
SCROLLBARS_BOTH

SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY SCROLLBARS_VERTICAL_ONLY

Using a TextArea
Methods : Supports the getText( ), setText( ), getSelectedText( ), select( ), isEditable( ), and
setEditable( ) methods. In addition to these, TextArea adds the following methods:

1. void append(String str) appends the string specified by str to the end of the current text. 2. void insert(String str, int index) inserts the string passed in str at the specified index 3. void replaceRange(String str, int startIndex, int endIndex)

replaces the characters from startIndex to endIndex1, with


the replacement text passed in str.

Using a TextArea
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

Using a TextArea

Using a TextArea sample output

Understanding Layout Managers


Each Container object has a layout manager associated with it.

The layout manager is set by the setLayout( ) method


void setLayout(LayoutManager layoutObj) layoutObj A reference to the desired layout manager

pass null for layoutObj If you wish to disable the


layout manager.

Understanding Layout Managers


Each layout manager keeps track of a list of components that are stored by their names.

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. Components are laid out from the upper-left corner, left to

right and top to bottom.


Constructors for FlowLayout

1. FlowLayout( )
2. FlowLayout(int how) 3. FlowLayout(int how, int horz, int vert)

FlowLayout
Constructors for FlowLayout 1. The first form creates the default layout, which centers

components and leaves five pixels of space between each


component 2. The second form lets you specify how each line is aligned.

Valid values for how are as follows:


1. 2. FlowLayout.LEFT FlowLayout.CENTER

3.
4. 5.

FlowLayout.RIGHT
FlowLayout.LEADING FlowLayout.TRAILING

FlowLayout
Constructors for FlowLayout 3. The third form allows you to specify the horizontal and

vertical space left between components


Here is a version of the CheckboxDemo applet( the controls are left aligned )

FlowLayout

FlowLayout

FlowLayout

FlowLayout
sample output

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.

BorderLayout
Constructors defined by BorderLayout 1. BorderLayout( ) Creates a default border layout. 2. BorderLayout(int horz, int vert)
Allows you to specify the horizontal and vertical

space left between components in horz and vert

BorderLayout defines the following constants that specify the


regions:
BorderLayout.CENTER

BorderLayout.SOUTH
BorderLayout.EAST BorderLayout.WEST BorderLayout.NORTH

Use these constants with the following form of add( ), which is defined by Container:

void add(Component compObj, Object region);

region specifies where the component will be added.

Here is an example of a BorderLayout with a component in each


layout area

Sample output

Using Insets
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

Insets getInsets( ) returns an Insets object that contains


the top, bottom, left, and right inset

Constructor for Insets Insets(int top, int left, int bottom, int right)

Using Insets
Here is the preceding BorderLayout example modified so that it
insets its components ten pixels from each border.

Using Insets

Using Insets

Using Insets
Output from the InsetsDemo applet

GridLayout
GridLayout lays out components in a two-dimensional grid. The constructors supported
1. GridLayout( ) creates a single-column grid layout 2. GridLayout(int numRows, int numColumns )

3. GridLayout(int numRows, int numColumns, int horz, int vert)


numRow , numColumns 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.

GridLayout
Here is a sample program that creates a 44 grid and fills it in with 15 buttons, each labeled with its index:

GridLayout

GridLayout
the output generated by the GridLayoutDemo applet:

CardLayout
It stores several different layouts Each layout can be thought of as being on a separate

index card in a deck


The deck can be shuffled so that any card is on top at a

given time
useful for user interfaces with optional components that can be dynamically enabled and disabled upon user input

CardLayout
Provides these two constructors 1. CardLayout( )

2.

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

STEPS to Create CardLayout


1. create a panel that contains the deck and a panel for each card in the deck

2. add to the appropriate panel the components that


form each card.

3. Add these panels to the panel for which CardLayout is


the layout manager 4. finally, you add this panel to the main applet panel

STEPS to Create CardLayout


Use this form of add( ) when adding cards to a panel: void add(Component panelObj, Object name);

name specifies the name of the card


panelObj specifies the panel
After you have created a deck, your program activates a card by
calling one of the following methods defined by CardLayout 1. 2. 3. 4. 5. void first(Container deck) void last(Container deck) void next(Container deck) void previous(Container deck) void show(Container deck, String cardName)

The following example creates a two-level card deck that allows the user to select an operating system.

output

Menu Bars and Menus

Menu Bars and Menus


Menu concept is implemented in Java by the following
classes : 1. MenuBar : contains one or more Menu objects 2. Menu : contains a list of MenuItem objects 3. MenuItem : represents something that can be selected by the user
Since Menu is a subclass of MenuItem, a hierarchy of nested submenus can be created.

Steps to create Menus


1. first create an instance of MenuBar
2. Next, create instances of Menu that will define the selections displayed on the bar

constructors for Menu:


1. Menu( ) 2. Menu(String optionName) 3. Menu(String optionName, boolean removable) optionName specifies the name of the menu selection. removable If removable is true, the pop-up removed and allowed to float free. menu can be

Steps to create Menus


To cretate menu items use MenuItems constructors :
1. MenuItem( ) 2. MenuItem(String itemName) 3. MenuItem(String itemName, MenuShortcut keyAccel) itemName the name shown in the menu,

keyAccel is the menu shortcut for this item.

Methods:
1. void setEnabled(boolean enabledFlag)

disable or enable a menu item


1. boolean isEnabled( )

returns true if the menu item on which it is called


is enabled.
2. void setLabel(String newName)

change the name of a menu item


3. String getLabel( )

retrieve the current name

CheckboxMenuItem You can create a checkable menu item by using a subclass of MenuItem called CheckboxMenuItem 1. CheckboxMenuItem( )

2. CheckboxMenuItem(String itemName)
3. CheckboxMenuItem(String itemName, boolean on)
itemName the name shown in the menu

on if on is true, the checkable entry is initially checked.

CheckboxMenuItem You can obtain the status of a checkable item by calling getState( ). You can set it to a known state by using setState( ).

boolean getState( ) returns true if checked. Otherwise, it

returns false
void setState(boolean checked) checked must be TRUE

to check an item

Adding Menu item and Menu Bar Add the item to a Menu object by using add( ), MenuItem add(MenuItem item) Item the item being added. 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)


menu the menu being added. The menu is returned

Handling Menus
Menus only generate events when an item of type MenuItem or CheckboxMenuItem is selected. Each time a menu item is selected, an ActionEvent object is generated. Each time a check box menu item is checked or unchecked, an ItemEvent object is generated Thus, you must implement the ActionListener and ItemListener

interfaces in order to handle these menu events.

Handling Menus
The getItem( ) method of ItemEvent returns a reference to the item that generated this event. Following is an example that adds a series of nested menus to a popup window. The item selected is displayed in the window.

Sample output

Dialog Boxes

Dialog Boxes
Dialog boxes are primarily used to obtain user input. Dialog boxes are always child windows of a top-level window dialog boxes dont have menu bars. Dialog boxes may be modal or modeless. When a modal dialog

box is active all input is directed to it until it is closed.


When a modeless dialog box is active, input focus can be directed to another window in your program

Dialog Boxes
Dialog boxes are of type Dialog.

Two commonly used constructors :


1. Dialog(Frame parentWindow, boolean mode) 2. Dialog(Frame parentWindow, String title, boolean mode)

parentWindow the owner of the dialog box.


mode
If mode is true, the dialog box is modal

title title of the dialog box


Generally, you will subclass Dialog, adding the functionality required by your application

Dialog Boxes
Following is a modified version of the preceding menu program that displays a modeless dialog box when the New option is

chosen.

sample output

FileDialog

FileDialog
To create a file dialog box, instantiate an object of type FileDialog. This causes a file dialog box to be displayed.

FileDialog provides these constructors: 1. FileDialog(Frame parent, String boxName) 2. FileDialog(Frame parent, String boxName, int how)

3. FileDialog(Frame parent)

FileDialog
parent the owner of the dialog box, boxName the name displayed in the boxs title bar. If boxName is omitted, the title of the dialog box is empty. how if FileDialog.LOAD, then the box is selecting a file for

reading.
If how is FileDialog.SAVE, the box is selecting a file for writing

FileDialog
FileDialog( ) provides the following methods 1. String getDirectory( )

2. String getFile( )
These methods return the directory and the filename, respectively.

The output generated by this program