0% found this document useful (0 votes)
3 views23 pages

Bca 2nd Java Notes - Ch4

The document discusses applets in Java, highlighting their execution in browsers and differences from applications, including lifecycle methods and event handling. It explains the delegation event model, where sources generate events and listeners respond to them, detailing various event types and listener interfaces. Additionally, it covers the two types of applets (local and remote) and provides examples of applet code and HTML integration.

Uploaded by

sowmyarani912
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views23 pages

Bca 2nd Java Notes - Ch4

The document discusses applets in Java, highlighting their execution in browsers and differences from applications, including lifecycle methods and event handling. It explains the delegation event model, where sources generate events and listeners respond to them, detailing various event types and listener interfaces. Additionally, it covers the two types of applets (local and remote) and provides examples of applet code and HTML integration.

Uploaded by

sowmyarani912
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

OBJECT ORIENTED PROGRAMMING WITH JAVA

UNIT 4: EVENT AND GUI PROGRAMMING

APPLETS:

An applet is a program that comes from server into a client and gets executed at client side anddisplays the
result.

An applet represents byte code embedded in a html page. (Applet = bytecode + html) and run with the help
of Java enabled browsers such as Internet Explorer.

An applet is a Java program that runs in a browser. Unlike Java applications applets do not havea main ()
method.

To create applet we can use [Link] or [Link] class. All applets inherit the super
class ”Applet‟. An Applet class contains several methods that help to control the execution of an applet.

Advantages:
 Applets provide dynamic nature for a webpage.
 Applets are used in developing games and animations.
 Writing and displaying (browser) graphics and animations is easier thanapplications.
 In GUI development, constructor, size of frame, window closing code etc. are notrequired

Restrictions of Applets of Applets Vs Applications


 Applets are required separate compilation before opening in a browser.
 In realtime environment, the bytecode of applet is to be downloaded from the server to theclient
machine
 Applets are treated as untrusted (as they were developed by unknown people and placed
onunknown servers whose trustworthiness is not guaranteed).
 Extra Code is required to communicate between applets using AppletContext.

1 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

DIFFERENCES BETWEEN APPLETS AND APPLICATIONS

FEATURES APPLICATIONS APPLET

Main() method Main( ) method present Main ( ) method not present

Execution Can be executed on Used to run a program on


standalone computer client browser like chrome
system(JDK and JRE)

Nature Called as stand-alone Requires some third party


application can be executed tool help like a browser to
from command prompt execute

Restrictions Can access any data or Cannot access anything on the


software available on the system except browser’s
system services

Security Does not require any security Requires highest security for
the system as they are
untrusted
Programming Larger programs Small programs

Platform Platform independent Platform independent

Accessibility The java applications are Applets are designed just for
design to work with the client handling the client side
as well as server problems

Working Applications are created by Applets are created by


writing public static void extending the
main(String[ ] s) method [Link] class

Client side/ server side The applications don’t have Applets are designed for the
such type of criteria client side programming
purpose

Methods Application has a single start Applet application has 5


point which is main method methods which will be
automatically invoked

2 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Example public class MyClass Import [Link].*;


{ Import [Link].*;
public static void main(String public class Myclass extends
args[ ]) Applet
{ } {
} public void init( )
{}
Public void start( )
{}
public void stop( )
{}
public void destroy( )
{}
public void paint(Graphics g)
{}
}

LIFE CYCLE OF AN APPLET


Let the Applet class extends Applet or JApplet class.

Initialization:
public void init(): This method is used for initializing variables, parameters to create components. This
method is executed only once at the time of applet loaded into memory.

public void init()


{
//initialization
}

3 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Runnning:

public void start (): After init() method is executed, the start method is executed automatically. Start
method is executed as long as applet gains focus. In this method code related to opening files and
connecting to database and retrieving the data and processing the data is written.

Idle / Runnable:

public void stop (): This method is executed when the applet loses focus. Code related to closing the files
and database, stopping threads and performing clean up operations are written in this stop method.

Dead/Destroyed:
public void destroy (): This method is executed only once when the applet is terminated from the memory.

Executing above methods in that sequence is called applet life cycle.

We can also use public void paint (Graphics g) in applets.

There are two ways to run an applet.

Executing an applet within a Java compatible web browser.

Executing an applet using „appletviewer‟. This executes the applet in a window.

To execute an applet using web browser, we must write a small HTML file which contains the appropriate
„APPLET‟ tag. <APPLET> tag is useful to embed an applet into an HTML page. It has the following form:

<APPLET CODE=”name of the applet class file” HEIGHT = maximum height of applet in pixels WIDTH
= maximum width of applet in pixels ALIGN = alignment (LEFT, RIGHT,MIDDLE, TOP, BOTTOM)>

<PARAM NAME = parameter name VALUE = its


value> </APPLET>

Execution: appletviewer [Link] or appletviewer [Link]

The <PARAM> tag useful to define a variable (parameter) and its value inside the HTML page which can
be passed to the applet. The applet can access the parameter value using getParameter () method, as: String
value = getParameter (“pname”);

4 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Example Program
Following is a simple applet named [Link] −
import [Link].*; import
[Link].*;
public class HelloWorldApplet extends Applet { public
void paint (Graphics g) {
[Link] ("Hello World", 25, 50);
}}
Invoking an Applet - [Link]
<html>
<title>The Hello, World Applet</title>
<applet code = "[Link]" width = "320" height = "120">
</applet>
</html>

OUTPUT: javac [Link]


appletviewer [Link]

TYPES OF APPLETS
Applets are of two types:
// Local Applets
// Remote Applets

Local Applets: An applet developed locally and stored in a local system is called local applets. So, local
system does not require internet. We can write our own applets and embed them into the web pages.
Remote Applets: The applet that is downloaded from a remote computer system and embed applet into a
web page. The internet should be present in the system to download the applet and run it. To download
the applet we must know the applet address on web known as Uniform Resource Locator(URL) and must
be specified in the applets HTML document as the value of CODEBASE.

5 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

EVENT HANDLING

Event handling is at the core of successful applet programming. Most events to which the applet will
respond are generated by the user. The most commonly handled events are those generated by the mouse,
the keyboard, and various controls, such as a push button.

Events are supported by the [Link] package.

The Delegation Event Model


The modern approach to handling events is based on the delegation event model, which defines standard and
consistent mechanisms to generate and process events.

Its concept is quite simple: a source generates an event and sends it to one or more listeners. In this scheme,
the listener simply waits until it receives an event. Once received, the listener processes the event and then
returns.

The advantage of this design is that the application logic that processes events is cleanly separated from the
user interface logic that generates those events. A user interface element is able to "delegate" the processing
of an event to a separate piece of code.

In the delegation event model, listeners must register with a source in order to receive an event notification.
This provides an important benefit: notifications are sent only to listeners that want to receive them.

EVENTS
In the delegation model, an event is an object that describes a state change in a source. It can be generated as
a consequence of a person interacting with the elements in a graphical user interface. Some of the activities
that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an
item in a list, and clicking the mouse.

Events may also occur that are not directly caused by interactions with a user interface. For example, an
event may be generated when a timer expires, a counter exceeds a value, software or hardware failure
occurs, or an operation is completed.

6 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

EVENT SOURCES
A source is an object that generates an event. This occurs when the internal state of that object changes in
some way. Sources may generate more than one type of event. A source must register listeners in order for
the listeners to receive notifications about a specific type of event. Each type of event has its own
registration method.

Here is the general form:


public void add Type Listener( Type Listener el )

EVENT LISTENERS
A listener is an object that is notified when an event occurs. It has two major requirements. First, it must
have been registered with one or more sources to receive notifications about specific types of events.
Second, it must implement methods to receive and process these notifications. The methods that receive and
process events are defined in a set of interfaces found in [Link].

For example, the MouseMotionListener interface defines two methods to receive notifications when the
mouse is dragged or moved.

EVENT CLASSES
The classes that represent events are at the core of Java's event handling mechanism. At the root of the Java
event class hierarchy is EventObject, which is in [Link]. It is the superclass for all events.

It’s one constructor is shown here:


EventObject(Object src )

EventObject contains two methods: getSource( ) and toString( ) .

The getSource( ) method returns the source of the event. Ex: Object getSource( )

toString( ) returns the string equivalent of the event.

7 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

The package [Link] defines several types of events that are generated by various user interface
elements.
Event Class Description
ActionEvent Generated when a button is pressed, a list item is double-clicked, or a menu
item is selected.
AdjustmentEvent Generated when a scroll bar is manipulated.
ComponentEvent Generated when a component is hidden, moved, resized or becomes visible.
ContainerEvent Generated when a component is added to or removed from a container.
FocusEvent Generated when a component gains or loses keyboard focus.
InputEvent Abstract super class for all component input event classes.
ItemEvent Generated when a check box or list item is clicked; so occurs when a choice
selection is made or a checkable menu item is selected or deselected.
KeyEvent Generated when input is received from the keyboard.
MouseEvent Generated when the mouse is dragged, moved, clicked, pressed, or released;
also generated when the mouse enters or exits a component.
MouseWheelEvent Generated when the mouse wheel is moved. (Added by Java 2, version 1.4)
TextEvent Generated when the value of a text area or text field is changed.
WindowEvent Generated when a window is activated, closed, deactivated, deiconified,
iconified, opened, or quit.

The ActionEvent Class

An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu item is
selected. The ActionEvent class defines four integer constants that can be used to identify any modifiers
associated with an action event: ALT_MASK , CTRL_MASK , META_MASK , and SHIFT_MASK .

ActionEvent has these three constructors:

ActionEvent(Object src , int type , String cmd )

ActionEvent(Object src , int type , String cmd , int modifiers )

ActionEvent(Object src , int type, String cmd, long when , int modifiers )

8 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

The ComponentEvent Class

// ComponentEvent is generated when the size, position, or visibility of a component is


changed. There are four types of component events. The constants and their meanings are
shown here:

COMPONENT_HIDDEN The component was hidden. COMPONENT_MOVED The component was


moved. COMPONENT_RESIZED The component was resized. COMPONENT_SHOWN The
component became visible.

The ContainerEvent Class

//ContainerEvent is generated when a component is added to or removed from a container.

There are two types of container events.


COMPONENT_ADDED and
COMPONENT_REMOVED

The KeyEvent Class

//KeyEvent is generated when keyboard input occurs. There are three types of key events, which are
identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED .

The first two events are generated when any key is pressed or released. The last event occurs only when a
character is generated.

The MouseEvent Class


There are eight types of mouse events. The MouseEvent class defines the following integer constants that
can be used to identify them:

MOUSE_CLICKED The user clicked the mouse.


MOUSE_DRAGGED The user dragged the mouse.
MOUSE_ENTERED The mouse entered a component.
MOUSE_EXITED The mouse exited from a component.
MOUSE_MOVED The mouse moved.
MOUSE_PRESSED The mouse was pressed.
MOUSE_RELEASED The mouse was released.
MOUSE_WHEEL The mouse wheel was moved (Java 2, v1.4).

9 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

The WindowEvent Class


There are ten types of window events. The WindowEvent class defines integer constants that can be used to
identify them. The constants and their meanings are shown here:

WINDOW_ACTIVATED The window was activated.

WINDOW_CLOSED The window has been closed.

WINDOW_CLOSING The user requested that the window be closed.


WINDOW_DEACTIVATED The window was deactivated.
WINDOW_DEICONIFIED The window was deiconified.
WINDOW_GAINED_FOCUS The window gained input focus.
WINDOW_ICONIFIED The window was iconified.
WINDOW_LOST_FOCUS The window lost input focus.
WINDOW_OPENED The window was opened.
WINDOW_STATE_CHANGED The state of the window changed

EVENT LISTENER INTERFACES


When an event occurs, the event source invokes the appropriate method defined by the listener and provides
an event object as its argument
Interface Description
ActionListener Defines one method to receive action events.
AdjustmentListener Defines one method to receive adjustment events.
ComponentListener Defines four methods to recognize when a component is hidden,
moved, resized, or shown.
ContainerListener Defines two methods to recognize when a component is added to or
removed from a container.
FocusListener Defines two methods to recognize when a component gains or losses
keyboard focus.
ItemListener Defines one method to recognize when the state of an item changes.
KeyListener Defines three methods to recognize when a key is pressed, released,
or typed.

10 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

MouseListener Defines five methods to recognize when the mouse is clicked, enters a
component, exits a component, is pressed, or is released.
MouseMotionListener Defines two methods to recognize when the mouse is dragged or
moved.
MouseWheelListener Defines one method to recognize when the mouse wheel is moved.
TextListener Defines one method to recognize when a text value changes.
WindowListener Defines seven methods to recognize when a window is activated,
closed, deactivated, deiconified, iconified, opened, or quit.

The delegation event model has two parts: sources and listeners. Listeners are created by implementing
one or more of the interfaces defined by the [Link] package.

The ActionListener Interface

This interface defines the actionPerformed( ) method that is invoked when an action eventoccurs.

Its general form is shown here: void actionPerformed(ActionEvent ae )

The ItemListener Interface

This interface defines the itemStateChanged( ) method that is invoked when the state of an itemchanges.

Its general form is shown here: void itemStateChanged(ItemEvent ie )

The KeyListener Interface

This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are invoked when a key
is pressed and released, respectively. The keyTyped( ) method is invoked when a character has been entered.
For example, if a user presses and releases the key, three events are generated in A sequence: key pressed,
typed, and released.

The general forms of these methods are shown here:


void keyPressed(KeyEvent ke )
void keyReleased(KeyEvent ke )
void keyTyped(KeyEvent ke )

11 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

The MouseListener Interface

This interface defines five methods. If the mouse is pressed and released at the same point, mouseClicked( )
is invoked. When the mouse enters a component, the mouseEntered( ) method is called. When it leaves,
mouseExited( ) is called. The mousePressed( ) and mouseReleased( ) methods are invoked when the mouse
is pressed and released, respectively.

The general forms of these methods are shown here:


void mouseClicked(MouseEvent me )
void mouseEntered(MouseEvent me )
void mouseExited(MouseEvent me )
void mousePressed(MouseEvent me )
void mouseReleased(MouseEvent me )

The MouseMotionListener Interface

This interface defines two methods. The mouseDragged( ) method is called multiple times as the mouse is
dragged. The mouseMoved( ) method is called multiple times as the mouse is moved.

Their general forms are shown here:


void mouseDragged(MouseEvent me ) void mouseMoved(MouseEvent me )

The TextListener Interface

This interface defines the textChanged( ) method that is invoked when a change occurs in a text area or text
field.

Its general form is shown here: void textChanged(TextEvent te )

Handling Keyboard Events

When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the keyPressed( )
event handler. When the key is released, a KEY_RELEASED event is generated and the keyReleased( )
handler is executed. If a character is generated by the keystroke, then a KEY_TYPED event is sent and the
keyTyped( ) handler is invoked.

Thus, each time the user presses a key, at least two and often three events are generated. If all you care
about are actual characters, then you can ignore the information passed by the key press and release events.

12 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

GUI PROGRAMMING WITH JAVA

ABSTRACT WINDOW TOOLKIT (AWT)

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based application in java. Java
AWT components are platform-dependent i.e. components are displayed according to the view of operating
system. AWT is heavyweight i.e. its components uses the resources of system. The Abstract Window
Toolkit(AWT) support for applets. The AWT contains numerous classes and methods that allow you to
create and manage windows.

The [Link] package provides classes for AWT api such as TextField, Label, TextArea, RadioButton,
CheckBox, Choice, List etc.

AWT Classes
The AWT classes are contained in the [Link] package. It is one of Java's largest packages.

Class Description

AWTEvent Encapsulates AWT events.

AWTEventMulticaster Dispatches events to multiple listeners.

BorderLayout Border layouts use five components:


North, South, East, West, and Center.
CardLayout Card layouts emulate index [Link] the 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.

Dimension Specifies the dimensions of an object. The width is stored in


width , and the height is stored in height .
13 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga
OBJECT ORIENTED PROGRAMMING WITH JAVA

Event Encapsulates events.


FlowLayout The flow layout manager. Flow layout positions components left
to right, top to bottom.
Frame Creates a standard window that has a title bar, resize corners, anda menu bar.
Graphics Encapsulates the graphics context

Control Fundamentals

The AWT supports the following types of controls:


o Labels
o Push buttons
o Check boxes
o Choice lists
o Lists
o Scroll bars
o Text editing

User interaction with the program is of two types:


CUI (Character User Interface): In CUI user interacts with the application by typing characters or
commands. In CUI user should remember the commands. It isnot user friendly.

GUI (Graphical User Interface): In GUI user interacts with the application through graphics. GUI is user
friendly. GUI makes application attractive. It is possible to simulate real object in GUI programs. In java to
write GUI programs we can use awt (Abstract Window Toolkit) package.

14 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Java AWT Class Hierarchy


The hierarchy of Java AWT classes is given below

Container
The Container is a component in AWT that can contain other components like buttons, textfields, labels
etc. The classes that extend Container class are known as container such as Frame, Dialog and Panel.

Window
The window is the container that has no borders and menu bars. You must use frame, dialog or another
window for creating a window.

Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components like
button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other components
like button, textfield etc.

15 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Useful Methods of Component class

Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int height) sets the size(width and height) of the component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by
default false.

Listeners and Listener Methods:

Listeners are available for components. A Listener is an interface that listens to an event from a
component. Listeners are available in [Link] package. The methods in the listener interface are to
be implemented, when using that listener.
Component Listener Listener methods
Button ActionListener public void actionPerformed(ActionEvent e)
Checkbox ItemListener public void itemStateChanged(ItemEvent e)
CheckBoxGroup ItemListener public void itemStateChanged(ItemEvent e)
TextField ActionListener public void actionPerformed(ActionEvent e)
FocusListener public void focusGained(FocusEvent e)
public void focusLost(FocusEvent e)
TextArea ActionListener public void actionPerformed(ActionEvent e)
FocusListener public void focusGained(FocusEvent e)
public void focusLost(FocusEvent e)

Choice ActionListener public void actionPerformed(ActionEvent e)


ItemListener public void itemStateChanged(ItemEvent e)
List ActionListener public void actionPerformed(ActionEvent e)
ItemListener public void itemStateChanged(ItemEvent e)
Scrollbar AdjustmentListener public void adjustmentValueChanged (AdjustmentEvent e)
MouseMotionListener public void mouseDragged(MouseEvent e)
public void mouseMoved(MouseEvent e)
Label No listener is needed

16 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Layout Managers
A layout manager arranges the child components of a container. It positions and sets the size of
components within the container's display area according to a particular layout scheme.

The layout manager's job is to fit the components into the available area, while maintaining the proper
spatial relationships between the components. AWT comes with a few standard layout managers that will
collectively handle most situations; you can make your own layout managers if you have special
requirements.

LayoutManager at work

Every container has a default layout manager; therefore, when you make a new container, it comes with a
LayoutManager object of the appropriate type. You can install a new layout manager at any time with the
setLayout() method. Below, we set the layout manager of a container to a BorderLayout:

setLayout ( new BorderLayout( ) );

Every component determines three important pieces of information used by the layout manager in placing
and sizing it: a minimum size, a maximum size, and a preferred size.

17 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

These are reported by the getMinimumSize(), getMaximumSize(), and getPreferredSize(), methods of


Component, respectively.

When a layout manager is called to arrange its components, it is working within a fixed area. It usually
begins by looking at its container's dimensions, and the preferred or minimum sizes of the child
components.

Layout manager types

Flow Layout

FlowLayout is a simple layout manager that tries to arrange components with their preferred sizes, from left
to right and top to bottom in the display. A FlowLayout can have a specified justification of LEFT,
CENTER, or RIGHT, and a fixed horizontal and vertical padding.

By default, a flow layout uses CENTER justification, meaning that all components are centered within the
area allotted to them. FlowLayoutis the default for Panelcomponents like Applet.

Grid Layout

GridLayout arranges components into regularly spaced rows and columns. The components are
arbitrarily resized to fit in the resulting areas; their minimum and preferred sizes are consequently
ignored.

GridLayout is most useful for arranging very regular, identically sized objects and for allocating
space for Panels to hold other layouts in each region of the container.

GridLayout takes the number of rows and columns in its constructor. If you subsequently give it
too many objects to manage, it adds extra columns to make the objects fit. You can also set the
number of rows or columns to zero, which means that you don't care how many elements the layout
manager packs in that dimension.

18 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Border Layout

BorderLayout is a little more interesting. It tries to arrange objects in one of five geographical
locations: "North," "South," "East," "West," and "Center," possibly with some padding between.

BorderLayout is the default layout for Window and Frame objects. Because each component is
associated with a direction, BorderLayout can manage at most five components; it squashes or stretches those
components to fit its constraints.

When we add a component to a border layout, we need to specify both the component and the position at
which to add it. To do so, we use an overloaded version of the add() method that takes an additional
argument as a constraint.

AWT controls

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

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.

Button class is useful to create push buttons. A push button triggers a series of events.
To create push button: Button b1 =new Button("label"); To get the label
of the button: String l = [Link](); To set the label of the button:
[Link]("label");
To get the label of the button clicked: String str = [Link]();

Check Boxes:
A check box is a control that is used to turn an option on or off. It consists of a small box that can either
contain a check mark or not. There is a label associated with each check box that describes what option the
box represents. You change the state of a check box by clicking on it. Check boxes can be used individually
or as part of a group.

19 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

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.

TextArea:
Sometimes a single line of text input is not enough for a given task. To handle these situations, the AWT
includes a simple multiline editor called TextArea .

CheckboxGroup

It is possible 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.
A Radio button represents a round shaped button such that only one can be selected from a panel.
Radio button can be created using CheckboxGroup class and Checkbox classes.

· To create a radio button: CheckboxGroup cbg = new CheckboxGroup ();


Checkbox cb = new Checkbox ("label", cbg, true);
· To know the selected checkbox: Checkbox cb = [Link] ();
·To know the selected checkbox label: String label = [Link]().getLabel ();

Choice Controls
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. Choice menu is a popdown list of items. Only one item can
be selected.

· To create a choice menu: Choice ch = new Choice();


· To add items to the choice menu: [Link] ("text");
· To know the name of the item selected from the choice menu:
String s = [Link] ();
· To know the index of the currently selected item: int i = [Link]();
This method returns -1, if nothing is selected.

20 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Lists
The List class provides a compact, multiple-choice, scrolling selection list. Unlike the Choice object, which
shows only the single selected item in the menu, a 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( )
List(int numRows )
List(int numRows , boolean multipleSelect )
A List box is similar to a choice box, it allows the user to select multiple items.

· To create a list box:


(or)

List lst = new List();

List lst = new List (3, true);

This list box initially displays 3 items. The next parameter true represents that the user can select more than
one item from the available items. If it is false, then the user can select onlyone item.

= To add items to the list box: [Link]("text");


= To get the selected items: String x[] = [Link]();
= To get the selected indexes: int x[] = [Link] ();

Scroll Bars

Scroll bars are used to select continuous values between a specified minimum and [Link] bars may
be oriented horizontally or vertically. Scrollbar class is useful to create scrollbars that can be attached to a
frame or text area. Scrollbars can be arranged vertically or horizontally.

21 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga


OBJECT ORIENTED PROGRAMMING WITH JAVA

Graphics

The AWT supports a rich assortment of graphics methods. All graphics are drawn relative toa window.
Graphics class and is obtained in two ways:

\} It is passed to an applet when one of its various methods, such as paint( ) or update( ), is
called.
\} It is returned by the getGraphics( ) method of Component.

Drawing Lines

Lines are drawn by means of the drawLine( ) method, shown here:

void drawLine(int startX, int startY, int endX, int endY)


drawLine( ) displays a line in the current drawing color that begins at startX,startY and ends
at endX,endY.

Drawing Rectangles

The drawRect( ) and fillRect( ) methods display an outlined and filled rectangle, respectively. They are shown
here:

void drawRect(int top, int left, int width, int height)


void fillRect(int top, int left, int width, int height)

The upper-left corner of the rectangle is at top,left. The dimensions of the rectangle are specified by width
and height.

To draw a rounded rectangle, use drawRoundRect( ) or fillRoundRect( ), both shown here:


void drawRoundRect(int top, int left, int width, int height,int xDiam, int yDiam)
void fillRoundRect(int top, int left, int width, int height, int xDiam, int yDiam)
22 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga
OBJECT ORIENTED PROGRAMMING WITH JAVA

Drawing Ellipses and Circles

To draw an ellipse, use drawOval( ). To fill an ellipse, use fillOval( ). These methodsare shown here:
void drawOval(int top, int left, int width, int height)
void fillOval(int top, int left, int width, int height)

Drawing Arcs

Arcs can be drawn with drawArc( ) and fillArc( ), shown here:

void drawArc(int top, int left, int width, int height, int startAngle,int sweepAngle)

void fillArc(int top, int left, int width, int height, int startAngle,int sweepAngle)

The arc is bounded by the rectangle whose upper-left corner is specified by top,left and whose width
and height are specified by width and height. The arc is drawn from startAngle through the angular
distance specified by sweepAngle. Angles are specified in degrees.

Drawing Polygons

It is possible to draw arbitrarily shaped figures using drawPolygon( ) and fillPolygon(), shown here:

void drawPolygon(int x[ ], int y[ ], int numPoints)


void fillPolygon(int x[ ], int y[ ], int numPoints)

The polygon’s endpoints are specified by the coordinate pairs contained within the x and y arrays. The
number of points defined by x and y is specified by numPoints. There are alternative forms of these methods
in which the polygon is specified by a Polygon object.

23 Prepared By : Sowmya Rani G S, Lecturer, Govt Science College, Chitradurga

You might also like