unit-3 New

Embed Size (px)

Citation preview

  • 8/6/2019 unit-3 New

    1/54

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63 #

    Event Handling

    Event Handling

    Different Mechanism (AWT Introduction) Delegation Event Model

    Event Classes

    Event Listener Interfaces

    Adapter and Inner Classes

    Working with windows

    Graphics and Text

    Learning Objective

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Using AWT Controls

    Layout Managers and Menus

    Handling Image

    Animation Sound and Video

    Java AppletBeans

    Swings

    Servlets

    All the various types of AWT events, are

    placed in a separate package calledjava.awt.event for the sake of convenience.

    The Abstract Window Toolkit (AWT) is

    ' -

    AWT Introduction

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    windowing, graphics, and user-interface

    widget toolkit. The AWT is now part of the

    Java Foundation Classes (JFC) The

    standard API for providing a graphical user

    interface (GUI) for a Java program.

  • 8/6/2019 unit-3 New

    2/54

    The AWT provides, among other things:

    1. A basic set of GUI widgets such as buttons,text boxes, and menus, etc.

    2. The core of the GUI event subsystem .

    3. The interface between the native windowin

    AWT Introduction

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .system and the Java application.

    4. Several layout managers.

    5. A java.awt.datatransfer package for use withthe Clipboard and Drag and Drop

    6.The interface to input devices such as mouse and

    keyboards.

    7.The AWT Native Interface, which enables rendering

    libraries compiled to native code to draw directly to

    an AWT Canvas object drawing surface.

    AWT Introduction

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    8. Access to the system tray on supporting systems

    9.The ability to launch some desktop applications

    such as web browsers and email clients from a

    Java application

    AWT- It is a package that contains classes, which are used to

    create interfaces and in event handling.Java.awt (package)

    Component

    AWT Definition

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Label Button Container Text Component

    Window

    Frame

    Panel

    TextField TextArea

  • 8/6/2019 unit-3 New

    3/54

    A component is an object that can be

    displayed on the screen and can interact with

    the user.

    It is like a button or scroll bar that has visual

    Component Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .

    special property like background color and

    font color.

    Component is an abstract class that

    encapsulate all of the attributes of a visual

    component.

    All user interface elements that are displayed

    Component

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    are subclasses of Component.

    A component object is responsible for

    remembering the current foreground and

    background colors and the currently selected

    text font.

    Container:- It is a subclass of Component

    class. It has additional methods that allowother Component objects to be nested withinit. Other Container objects can be storedinside of a Container (since they are

    Container

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .various Layout Managers.

  • 8/6/2019 unit-3 New

    4/54

    Panel:- It is a concrete subclass of a Container.

    It doesnt add any new methods; it simply

    implements Container.

    Panel is a superclass for Applet.

    Panel

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    ,

    it is drawn on the surface of a Panel object.

    Panel is a window that does not contain a

    title bar, Menu bar, or border.

    When you run an applet using an applet

    viewer, the applet viewer provides the title

    and border.

    Other components can be added to a panel

    Panel Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .

    container).

    Once these components have been added,

    you can position and resize them manually

    using the setLocation(), setSize(), or

    setBounds() methods defined by Component.

    Window:- The window class creates a top-level

    window. A top-level window is not contained within

    any other object; it sits directly on the

    Windows

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .

    Generally we wont create window objects

    directly, instead will use a subclass of

    Window called Frame.

  • 8/6/2019 unit-3 New

    5/54

    Frame:- sub class of a Window .

    It has a title bar, menu bar, borders, and

    resizing corners.

    When a Frame window is created by a

    Frame

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    program a norma w n ow s crea e ra er

    than an applet).

    Canvas:- Although it is not part of the hierarchy for

    applet or frame window, there is one another type

    of window called Canvas.

    Canvas encapsulates a blank window upon which

    you can draw.

    Canvas

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    ButtonsCommon buttons

    Radio buttons

    GUI components

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

  • 8/6/2019 unit-3 New

    6/54

    GUI components

    Combo boxes

    Lists

    Menus

    GUI components

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Spinners

    Sliders

    GUI components

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Textfields

    Delegation Event Model

    Event model is based on the concept of an

    Event Source and Event Listeners. Any object that generates these messages (or

    events) is called an Event Source.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    . .

    event.

  • 8/6/2019 unit-3 New

    7/54

    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.

    Delegation Event Model

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    are provided by the source that generates

    events.

    Any object that is interested in receiving

    messages (or events ) is called an Event

    Listener.

    i.e. A listener is an object that is notified

    Delegation Event Model

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .

    It has two major requirements:

    1. It must have been registered (add) withone or more sources to receives

    notifications about specific types of events.

    Delegation Event Model

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .

    process these notifications.

  • 8/6/2019 unit-3 New

    8/54

    According to Sun, the reasons for coming

    out with the Java 1.1 Delegation Event

    Model are:

    1. A source generates an event and sends it

    Delegation Event Model

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .

    2. In this scheme, the listener simply waits

    until it receives an event.

    3. Once received, the listener processes the

    event and then return.

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

    Delegation Event Model

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .

    delegate the processing of an event to a

    separate piece of code.

    6. In this event model, listener must register

    with a source in order to receive an eventnotification. This provide an important

    benefit: notification are sent only to listeners

    that want to receive them.

    Delegation Event Model

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    7. This is a more efficient way to handle events

    than the design used by the old java 1.0

    approach.

  • 8/6/2019 unit-3 New

    9/54

    Old java 1.0 approach:- an event waspropagated up the containment hierarchyuntil it was handled by a component. Thisrequired components to receive events that

    they did not process, and it wasted valuable

    Delegation Event Model

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .

    Note: The delegation model eliminates thisoverhead.

    8. Facilitate the creation of robust eventhandling code which is less error-prone(strong compile-time checking)

    Methods of component class-

    1. void setVisible(boolean);

    2. void show();

    3. void hide();

    4. void enable boolean

    Methods of component class

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .

    5. void disable(boolean)

    6. void setSize(int w,int height);

    7. void setLocation(int left, int top);

    8. void setBounds(int left,int top, int w,int h);

    9. Add(object of control)

    Steps for creating GUI:

    Create object of container

    Create objects of control

    Customize appearance of container and

    Steps for creating GUI

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    contro s

    Add controls on container

    Show container

  • 8/6/2019 unit-3 New

    10/54

    Events: In the delegation model, an event is an

    object that describes a state change in a

    source.

    Some of the activities that cause events to be

    Events

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    ,

    character via the keyboard, selecting an

    item in a list, and clicking the mouse, etc.

    Events may also occur that are not directly

    caused by interactions with a user interface.

    e.g. an event may be generated when a

    timer expires, a counter exceeds a value,

    Events Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    ,

    an operation is completed, etc.

    Event Delegation Model is based on four

    concepts:1. The Event Classes

    2. The Event Listeners

    3. Ex licit Event Enablin

    Event Delegation Model is based on four concepts

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    4. Adapters

  • 8/6/2019 unit-3 New

    11/54

    At the root of the java event class hierarchy

    is EventObject, which is an java.util.

    It is the superclass for all events.

    EventObject contains two methods:

    Event Delegation Model is based on four concepts

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .

    getSource()- method returns the source of

    the event.

    toString()- returns the string equivalent of the

    event.

    ActionEvent generated by component activation

    AdjustmentEvent generated by adjustment of adjustable components

    such as scroll bars

    ContainerEvent generated when components are added to or removed

    from a container

    FocusEvent generated when a component receives input

    focus

    1. Event Class

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    ItemEvent generated when an item is selected from a list,

    choice or check box

    KeyEvent generated by keyboard activity

    MouseEvent generated by mouse activity

    PaintEvent generated when a component is painted

    TextEvent generated when a text component is modifiedWindowEvent generated by window activity like minimizing or

    maximizing

    Listeners for Different Events

    For each event type that can occur, theapplication can add event listeners, that have

    methods invoked when the event occurs.

    2. Event Listener

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    ,

    that an actual listener has to implement these

    methods.

  • 8/6/2019 unit-3 New

    12/54

    The names of the listener classes are simply

    derived from the names of the events they

    handle,

    MouseEvent's have two different types of

    2. Event Listener

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .

    (MouseListener and MouseMotionListener)

    Listener- Compare and matches the application

    with its event. Every listener in java is an

    interface .Hence, need to implement.

    Steps:

    Event Handling Steps

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    . .

    2. Give body to all the methods of listener

    Interfaces.

    3. Register the control on which the event isgenerated. (b.addActionlistner(this))

    An event listener may be removed from an

    Event Source's list of interested Listeners bycalling a remove...Listener() method, passing

    in the listener object to be removed.

    Event Handling Steps Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    , ,

    the code below removes the action listener

    object listenerObject from the button

    m_Button.

    m_Button.removeActionListener( listenerObject );

  • 8/6/2019 unit-3 New

    13/54

    Any number of event listener objects can

    listen for all kinds of events from any number

    of event source objects.

    e.g. a program might create one listener per

    Listeners

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    single listener for all events from

    all sources.

    Multiple listeners can register to be notified of

    events of a particular type from a particular

    source.

    Also, the same listener can listen to

    Listeners

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    not cat ons rom erent o ects.

    Each type of listeners can be notified only for

    its corresponding types of events which canbe generated by specific types of sources.

    Listeners

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

  • 8/6/2019 unit-3 New

    14/54

    Many buttons can register the same listener

    since all buttons generate the same type of

    event. This type of event may be generated

    by other types of sources as well.

    Multiple sources, single listener

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    button1

    ListItem3

    button2

    ActionListener

    A single source may generate different types

    of events and thus register multiple listeners.

    Single source, multiple listeners

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    MouseMotionListener

    MouseWheel ListenerMouseWheelEvent

    You implement an interface to create a

    listener.

    In the case of a single source that generates

    multiple types of events you can create a

    Listeners as interfaces

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    (remember: a class may extend only one

    superclass but implement more than one

    interfaces).

  • 8/6/2019 unit-3 New

    15/54

    MouseWheel

    ListenerMouseWheelEvent

    Single source, multiple listeners again

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    MouseMotion

    Listener

    MouseWheel +

    MouseMotion

    Listener

    To handle an event you need 3 steps:

    Implement the appropriate interface that

    will produce your listener class.

    Create a listener object.

    Event handling steps

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Register the listener to the source of

    interest.

    You register a listener using the

    corresponding add function in the form:

    component.addSomeListener(listener_object);

    You can find the source of an event by using

    Putting it into code

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    e ge ource me o :

    event_object.getSource();

  • 8/6/2019 unit-3 New

    16/54

    Event Listener MethodActionEvent ActionListener actionPerformed()

    AdjustmentEvent AdjustmentListener adjustmentValueChangd()

    ComponentEvent ComponentListener componentResized()

    componentMoved()

    componentShown()

    componentHidden()

    Listeners for Each Event

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    FocusEvent FocusListener focusGained()

    focusLost()

    ItemEvent ItemListener itemStateChanged()

    KeyEvent KeyListener keyTyped()

    keyPressed()

    keyReleased()

    MouseEvent MouseListener mouseClicked()

    mouseEntered()

    mouseExited()

    mousePressed()

    mouseReleased()

    MouseMotionListener

    mouseDragged()

    Listeners for Each Event

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    mouseMoved()

    WindowEvent WindowListener

    windowClosed()

    windowClosing()

    windowDeiconified()

    windowIconified()windowOpened()

    The following table lists which objects can have whichlistener types added:

    GUI Object Listener

    Button ActionListener

    Choice ItemListener

    Listeners for Object

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Checkbox ItemListener

    Component ComponentListener

    FocusListener

    KeyListener

    MouseListener

    MouseMotionListener

    Dialog WindowListener

  • 8/6/2019 unit-3 New

    17/54

    Frame WindowListener

    List ActionListener,ItemListener

    MenuItem ActionListener

    Scrollbar AdjustmentListener

    TextField ActionListener

    Listeners for Each Event

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Note that everyGUI object that inherits from

    Component can have Component, Focus, Key,

    Mouse and MouseMotion listeners added.

    Action events are generated for the following

    objects:

    GUI Object Action

    Button Click on Button

    Action Events

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    st ou e-c c on an tem

    MenuItem Click on MenuItem

    TextField Press key

    Item events are generated for the following objects:

    GUI Object ActionChoice Click on item

    Checkbox Select an item

    Deselect an item

    Item Events

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    List Select an item

    Deselect an item

    Extend a selection

    Reduce a selection

  • 8/6/2019 unit-3 New

    18/54

    A subclass can handle its own events by

    adding itself as a listener.

    In Explicit Event Handling, you control the

    order.

    3. Listeners vs. Explicit Enabling Event

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Java provides adapter classes that

    implements the corresponding listener

    interface containing more than one method.

    The methods in the classes are empty. The

    4. Adapter class

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Adapter class and override the methods that

    you need.

    Adapter classes are fully abstract classes

    that correspond to listener interfaces.

    They are extended (not implemented) and

    thus you can ignore methods that do not

    Adapter classes Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .

    You can use them instead of listeners in the

    case that only some of the methods of the

    interface are to be used.

  • 8/6/2019 unit-3 New

    19/54

    You dont use the abstract specifier and of

    course you cannot use multiple inheritance.

    Some adapter classes:

    KeyAdapter (instead of KeyListener)

    Adapter classes Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    ouse apter ouse stener

    MouseMotionAdapter

    (MouseMotionListener) etc

    Event listeners often define many methods.

    Since they are interface, you must implement

    all of them.

    Alternative: Subclass an appropriate adapter

    Adapter classes Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    an overr e on y e one you nee .

    Adapter Class Listener Interface

    ComponentAdapter ComponentListener

    Adapter Classes

    Adapter classes Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    on a ner ap er on a ner s ener

    FocusAdapter FocusListener

    KeyAdapter KeyListener

    MouseAdapter MouseListener

    MouseMotionAdapter MouseMotionListener

    WindoAdapter WindowListener

  • 8/6/2019 unit-3 New

    20/54

    import java.applet.*;

    import java.awt.*;

    import java.awt.event.*;

    public class MouseAdapterDemo extends

    Applet {

    Adapter classes Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    public void init() {

    setBackground(Color.green);

    addMouseListener(newMyMouseAdapter(this));

    }}

    class MyMouseAdapter extends MouseAdapter {

    MouseAdapterDemo mad;

    public MyMouseAdapter(MouseAdapterDemo mad){

    this.mad = mad;

    Adapter classes Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    }

    public void mousePressed(MouseEvent me) {

    mad.setBackground(Color.red);

    mad.repaint();}

    public void mouseReleased(MouseEvent me) {

    mad.setBackground(Color.green);mad.repaint();

    }

    }

    Adapter classes Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

  • 8/6/2019 unit-3 New

    21/54

    There are three methods of event handling:-

    1. Outer class

    2. Inner class

    3. Same class

    Methods of event Handling

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Notes:: Inner classes also called nested

    classes and these are declared within other

    classes.

    Anonymous Class

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    program are called anonymous class.

    An anonymous class cannot have a

    constructor as the class has no name.

    You may create all different classes

    independently and put them in separate files. you can implement your listeners inside the

    class that extends your Frame, making it aninner class.

    Inner classes

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    This enables you to put everything in oneclass (and hence in one file).

  • 8/6/2019 unit-3 New

    22/54

    import java.applet.*;import java.awt.*;import java.awt.event.*;/*

    Inner Classes

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    */public class MouseInnerDemo extendsApplet {

    public void init() {

    setBackground(Color.green);

    addMouseListener(new MyMouseAdapter());

    }

    class MyMouseAdapter extends MouseAdapter {

    Inner Classes Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    public void mousePressed(MouseEvent me) {

    setBackground(Color.red);

    repaint();}

    public void mouseReleased(MouseEvent me) {

    setBackground(Color.green);

    repaint();} }}

    import java.applet.*;import java.awt.*;import java.awt.event.*;/*

    */

    public class MouseAnonymousDemo extends Applet {

    Anonymous Inner Classes

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    public void init() {setBackground(Color.green);

    addMouseListener(new MouseAdapter() {

    public void mousePressed(MouseEvent me) {setBackground(Color.red);repaint();

    }

  • 8/6/2019 unit-3 New

    23/54

    public void mouseReleased(MouseEvent me) {

    setBackground(Color.green);

    repaint();

    }

    Anonymous Inner Classes Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    }

    }

    AnAn Anonymous Inner ClassAnonymous Inner Class

    What is the difference between a GUI and a

    console app?

    From the programmers perspective?

    A console app enables interaction through a

    Console vs. GUI applications

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    spec e ow o s.

    A GUI app makes it much more flexible. The

    user is allowed to perform combinations of

    actions.

    Class Frame

    java.lang.Object

    java.awt.Component

    Working with Windows

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    java.awt.Container

    java.awt.Window

    java.awt.Frame

  • 8/6/2019 unit-3 New

    24/54

    A Frame is a top-level window with a title anda border.

    The size of the frame includes any areadesignated for the border. The dimensions of

    the border area may be obtained using the

    Working with Frame Windows Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    get nsets met o , owever, s nce t esedimensions are platform-dependent, a validinsets value cannot be obtained until theframe is made displayable by either callingpack or show. Since the border area isincluded in the overall size of the frame, the

    border effectively obscures a portion of theframe, constraining the area available forrendering and/or displaying subcomponentsto the rectangle which has an upper-leftcorner location of (insets.left, insets.top), and

    Working with Frame Windows Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    - . .by height - (insets.top + insets.bottom).

    The default layout for a frame isBorderLayout.

    Frame()//creates a standard window that does not contain a title.

    Frame(String title) //creates a window withthe title specified by title.Methods

    Setting the windows dimension

    void setSize(int w,int h);

    Working with Frame Windows Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    setVisible(boolean flag)

    Setting a window title

    void setTitle(String str)

    Closing a frame window

    setVisible(false)

  • 8/6/2019 unit-3 New

    25/54

    Frame:

    Frame()-

    Frame(String)-

    Frame f=new Frame(calculator);

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    setTitle(String), f.setTitle(Calculator)

    getTitle(String)

    setLayout(null)

    Label -is a control that is used for displaying

    messages or output.

    1.Label()

    2.Label(String)

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    a e = new a e

    l.setText()

    l.getText()

    TextField- is a control used for single line

    input.1. TextField()

    2. TextFieldl(String)

    Working with Frame Windows

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    set ext get ext

  • 8/6/2019 unit-3 New

    26/54

    Button

    Button b=new Button(ok)

    Method-

    b.setLabel(String)

    Working with Frame Windows

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    b.getLabel(String)

    e.g. Button

    1.EventName -ActionEvent

    getSource()-generate reference of event

    object.

    Working with Windows

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    . stener - ct on stener

    Method is

    public void actionPerformed(ActionEvent e)

    3.To Register -addActionListener

    java.lang.Object

    java.awt.Graphicspublic abstract class Graphics extends Object

    The Graphics class is the abstract base class for all graphics

    contexts that allow an application to draw onto components

    that are realized on various devices, as well as onto off-

    Working with Graphics

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    screen images.

    (public class Object

    Class Object is the root of the class hierarchy. Every class has

    Object as a superclass. All objects, including arrays,

    implement the methods of this class.)

  • 8/6/2019 unit-3 New

    27/54

    drawLine

    public abstract void drawLine(int x1, int y1, int x2,

    int y2)

    Draws a line, using the current color, between the points

    (x1, y1) and (x2, y2) in this graphics context's coordinate

    Drawing Lines

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .

    Parameters:

    x1 - the first point's xcoordinate.

    y1 - the first point's ycoordinate.

    x2 - the second point's xcoordinate.

    y2 - the second point's ycoordinate.

    import java.awt.*;

    import java.applet.*;

    public class Lines extends Applet

    {

    ublic void aint Gra hics

    Drawing Lines Example

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    {

    g.drawLine(40,25,250,180);

    g.drawLine(75,90,400,400);

    }

    }

    drawRect

    public void drawRect(int x, int y, int width, int height) Draws the outline of the specified rectangle. The left and

    right edges of the rectangle are at x and x + width. Thetop and bottom edges are at y and y + height. Therectangle is drawn using the graphics context's current

    Drawing Rectangles

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .

    Parameters:

    x - the xcoordinate of the rectangle to be drawn.

    y - the ycoordinate of the rectangle to be drawn.

    width - the width of the rectangle to be drawn.

    height - the height of the rectangle to be drawn

  • 8/6/2019 unit-3 New

    28/54

    fillRect

    public abstract void fillRect(int x, int y, int width, int height)

    Fills the specified rectangle. The left and right edges of

    the rectangle are at x and x + width - 1. The top and

    bottom edges are at y and y + height - 1. The resulting

    rectangle covers an area width pixels wide by height

    Drawing Rectangles Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    pixels tall. The rectangle is filled using the graphics

    context's current color.

    Parameters:

    x - the xcoordinate of the rectangle to be filled.

    y - the ycoordinate of the rectangle to be filled.

    width - the width of the rectangle to be filled.

    height - the height of the rectangle to be filled.

    import java.awt.*;

    import java.applet.*;

    public class Lines extends Applet

    {

    ublic void aint Gra hics

    Drawing Rectangle Example

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    {

    g.drawRect(10,10,60,50);

    g.fillRect(100,10,60,50);

    }

    }

    drawRoundRect

    public abstract void drawRoundRect(int x, int y, int width,int height, int arcWidth, int arcHeight) Draws an outlined round-cornered rectangle using this graphics

    context's current color. The left and right edges of the rectangle areat x and x + width, respectively. The top and bottom edges of therectangle are at y and y + height.

    Drawing Rounded Rectangle

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Parameters:

    x - the xcoordinate of the rectangle to be drawn.

    y - the ycoordinate of the rectangle to be drawn.

    width - the width of the rectangle to be drawn.

    height - the height of the rectangle to be drawn.

    arcWidth - the horizontal diameter of the arc at the four corners.

    arcHeight - the vertical diameter of the arc at the four corners.

  • 8/6/2019 unit-3 New

    29/54

    fillRoundRect

    public abstract void fillRoundRect(int x, int y,int width, int height, int arcWidth, int arcHeight) Fills the specified rounded corner rectangle with the

    current color. The left and right edges of the rectangle are

    at x and x + width - 1, respectively. The top and bottom

    Drawing Rounded Rectangle Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    e ges o e rec ang e are a y an y + e g - .

    Parameters:

    x - the xcoordinate of the rectangle to be filled.

    y - the ycoordinate of the rectangle to be filled.

    width - the width of the rectangle to be filled.

    height - the height of the rectangle to be filled.

    import java.awt.*;

    import java.applet.*;

    public class Lines extends Applet

    {

    ublic void aint Gra hics

    Drawing Rounded Rectangle Example.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    {

    g.drawRoundRect(190,10,60,50,15,15);

    g.fillRoundRect(70,90,140,100,30,40);

    }

    }

    drawOval

    public abstract void drawOval(int x, int y, int width,int height) Draws the outline of an oval. The result is a circle or

    ellipse that fits within the rectangle specified by the x, y,width, and height arguments. The oval covers an area

    Drawing Oval Example.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    a s w + p xe s w e an e g + p x e s a .

    Parameters:

    x - the xcoordinate of the upper left corner of the oval to bedrawn.

    y - the ycoordinate of the upper left corner of the oval to bedrawn.

    width - the width of the oval to be drawn.

    height - the height of the oval to be drawn.

  • 8/6/2019 unit-3 New

    30/54

    fillOval

    public abstract void fillOval(int x, int y, int width,int height) Fills an oval bounded by the specified rectangle with the

    current color.

    Fill Oval Example

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Parameters:

    x - the xcoordinate of the upper left corner of the oval to befilled.

    y - the ycoordinate of the upper left corner of the oval to befilled.

    width - the width of the oval to be filled.

    height - the height of the oval to be filled.

    drawArc

    public abstract void drawArc(int x, int y, int width, int height,int startAngle, int arcAngle)

    Draws the outline of a circular or elliptical arc coveringthe specified rectangle. The resulting arc begins atstartAngle and extends for arcAngle degrees, using thecurrent color. Angles are interpreted such that 0 degrees

    '

    Draw Arc Example

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .counter-clockwise rotation while a negative valueindicates a clockwise rotation.

    The center of the arc is the center of the rectangle whoseorigin is (x, y) and whose size is specified by the widthand height arguments.

    The resulting arc covers an area width + 1 pixels wide byheight + 1 pixels tall.

    The angles are specified relative to the non-squareextents of the bounding rectangle such that 45 degrees

    always falls on the line from the center of the ellipse tothe upper right corner of the bounding rectangle. As aresult, if the bounding rectangle is noticeably longer inone axis than the other, the angles to the start and end ofthe arc segment will be skewed farther along the longeraxis of the bounds.

    Draw Arc Example Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Parameters:

    x - thexcoordinate of the upper-left corner of the arc to be drawn.

    y - the ycoordinate of the upper-left corner of the arc to be drawn.width - the width of the arc to be drawn.

    height - the height of the arc to be drawn.

    startAngle - the beginning angle.

    arcAngle - the angular extent of the arc, relative to the start angle.

  • 8/6/2019 unit-3 New

    31/54

    fillArc

    public abstract void fillArc(int x, int y, int width, int height,int startAngle, int arcAngle)

    Fills a circular or elliptical arc covering the specifiedrectangle. The resulting arc begins at startAngle andextends for arcAngle degrees. Angles are interpreted

    such that 0 degrees is at the 3 o'clock position. A positive-

    Fill Arc Example Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    negative value indicates a clockwise rotation.

    The center of the arc is the center of the rectangle whoseorigin is (x, y) and whose size is specified by the widthand height arguments.

    The resulting arc covers an area width + 1 pixels wide byheight + 1 pixels tall.

    The angles are specified relative to the non-squareextents of the bounding rectangle such that 45 degreesalways falls on the line from the center of the ellipse tothe upper right corner of the bounding rectangle. As aresult, if the bounding rectangle is noticeably longer inone axis than the other, the angles to the start and end ofthe arc segment will be skewed farther along the longeraxis of the bounds.

    Fill Arc Example Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Parameters:

    x - the xcoordinate of the upper-left corner of the arc to be filled.

    y - the ycoordinate of the upper-left corner of the arc to be filled.width - the width of the arc to be filled.

    height - the height of the arc to be filled.

    startAngle - the beginning angle.

    arcAngle - the angular extent of the arc, relative to the start angle.

    drawString

    public abstract void drawString(String str, int x, int y) Draws the text given by the specified string, using this

    graphics context's current font and color. The baseline of

    the leftmost character is at position (x, y) in this graphics

    '

    Draw String Example

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .

    Parameters:

    str - the string to be drawn.

    x - the xcoordinate.

    y - the ycoordinate.

    Etc.

  • 8/6/2019 unit-3 New

    32/54

    Text strings

    You already met the instruction used todisplay strings on the screen. In case youdidn't, you won't be surprised to hear that it is

    drawString. Just to remind you - a string is a

    Draw String Example Cont

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    p ece o text, anyt ng rom a s ng echaracter (a term which includes letters,punctuation, symbols such as @ or ^, andeven the space character) to a wholesentence. Strings are specified by placingthem within double quotation marks.

    The method drawString is given three parametersbetween brackets. The first item is the string itselfto be displayed on the screen. The other twonumbers specify where the string is to appear. Itrepresents the top-left corner of the string.However, the second number actually specifies the

    Draw String Example Cont

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    y-co-ordinate of a line on which the text sits. Somecharacters, such as 'g' or 'y' will drop down belowthis imaginary line, as shown in the followingexample:

    g.drawString("This is hugely easy",40,60);

    If you don't specify a colour for drawing shapes or

    text, then Java uses the default colour of black.

    Specifying a colour is fairly easy - although you

    can only specify one of 13 standard colours

    Working with colors

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .

    There is a standard method built into graphics

    environment variables called setColor (note the

  • 8/6/2019 unit-3 New

    33/54

    American spelling of 'Color'). It expects to be

    given a colour name, but the colour name

    must be of a standard type specified in yet

    another class called Color. What all this

    means is that colours are chosen as follows:

    Working with colors Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    g.setColor(Color.blue);

    g.setColor(Color.orange);

    Here are the thirteen standard colours. Make

    sure you use them exactly as specified -

    don't alter the case of the letters or insert

    spaces in the middle of them, and note the

    s ellin of 'Gra '.

    Working with colors Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Black Gray Orange Yellow Blue

    Green Pink Cyan lightGray Red

    darkGray Magenta white

    Any colour that you choose will then be used

    for drawing all lines, text, shapes and as thefill-in colour for shapes until you choose

    another colour. You can also determine the

    colour of the back round to the a let. This

    Working with colors Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    is done using the following instruction:

    setBackground(Color.cyan);

    Again, like the setColor method, it is

    important to note that the name of the

    method is all lower case letters except for the

  • 8/6/2019 unit-3 New

    34/54

    capital B in the middle. However, please note

    that setBackground is not part of the graphics

    environment, and as such, does not need to

    be preceded by g. In fact, if you do put g. at

    the be innin then the Java com iler

    Working with colors Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    ,complains. I have fallen into this trap many

    times!

    repaint

    Occasionally, there will be points in theprogram where you will want it redraw thescreen. Perhaps the screen has changed(the paint method can easily cope with if

    Working with repaint()

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    statements t at get t to raw erent t ngsin different circumstances). To call the paintmethod in these circumstances, use thefollowing instruction:

    repaint(); Note that there are no parameters

    (no numbers, strings or graphicsenvironments) passed to this method, but

    you still must include the two brackets and

    follow them with the obli ator semicolon,

    Working with repaint()0.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    like this ();

    It is vital that you don't include this method

    inside the paint method itself. If you did, the

    paint method would never terminate, as it

    would always be calling itself.

  • 8/6/2019 unit-3 New

    35/54

    Controls are components that allows a user tointeract with your application in various ways- e.g. acommonly used control is the push button.

    The AWT supports the following types of controls:

    Lables

    Push buttons

    Using AWT Controls

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Check boxes

    Choice lists

    Lists

    Scroll bars

    Text editing

    These controls are subclass of Component.

    Adding and Removing Controls

    To include a control in a window, you must add it tothe window by using add() method, which is definedby container.

    Using AWT Controls Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Compobj=is an instance of the control that you wantto add.a reference to compobjc is returned.

    Once a control has been added it will automatically be

    visible whenever its parent window is displayed.void remove(Componenet obj) and removeAll() are

    used.// to remove control from a window

    Responding to controls

    Except for Labels, which are passive controls, all controlsgenerate events when they are accessed by the user.

    Labels

    Using AWT Controls Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .

    Label()

    Label(String str)

    Label(String str, int how)

    Where Label.LEFT, Label.RIGHT, Label.CENTER

  • 8/6/2019 unit-3 New

    36/54

    Buttons

    A push button is a componenet that contains a label

    and that generates an event when it is pressed.

    These are objects of type Button.

    Button()

    Using AWT Controls Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Button(String str)

    Choice and List

    Event- ItemEvent

    Listener- ItemListener

    Method- public void

    Using AWT Controls Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    ItemStateChanged(ItemEvent e)

    Register- addItemListener(ItemListener)

    Scrollbar (horizontal/vertical)

    Event- AdjustmentEvent

    Listener- AdjustmentListener

    Method- public void

    Using AWT Controls Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    AdjustmentValueChanged(AdjustmentEvent

    e)

    Register- addAdjustmentListener(ItemListener)

  • 8/6/2019 unit-3 New

    37/54

    CheckBox- Multiple Selection

    checkBox(String)

    e.g. checkBox c=new CheckBox(string);

    checkBox(string,Boolean)

    Using AWT Controls Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    e.g. checkBox c1=new CheckBox(study,true);

    RadioButton- Single Selection

    checkBox(String,Boolean,CheckBoxGroupobject)

    e.g. checkBoxGroup cg=new CheckBoxGroup(string);

    checkBox c=new CheckBox(Male,true,cg);

    Using AWT Controls Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    e.g. checkBox c1=new CheckBox(Female,false,cg);

    You use layout managers to design your GUIs.

    There are several managers like:

    FlowLayout

    BorderLayout

    Layout Managers

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    GridLayout

    CardLayout

    GridBagLayout

  • 8/6/2019 unit-3 New

    38/54

    Default layout

    Components laid out from the top-left corner,

    from left to right and top to bottom like a text.

    FlowLayout

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    BorderLayout

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Places components in up to five areas: top, bottom, left,

    right, and center. All extra space is placed in the center

    area

    GridLayout

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Simply makes a bunch of components

    equal in size and displays them in the

    requested number of rows and columns

  • 8/6/2019 unit-3 New

    39/54

    lets you implement an

    area that contains

    different components at

    different times.

    A CardLayout is often

    controlled by a combo

    CardLayout

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    box, with the state of

    the combo box

    determining which

    panel (group of

    components) the

    CardLayout displays.

    is a sophisticated, flexible layout manager. It

    aligns components by placing them within a

    grid of cells, allowing some components to

    span more than one cell.

    GridBagLayout

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Putting it into code:

    Setting the manager:Container myCont = getContentPane();myCont.setLayout(new FlowLayout());

    Layout Managers Code

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    ng omponen s:

    myCont.add(aComponent, BorderLayout.WEST);

  • 8/6/2019 unit-3 New

    40/54

    The java.awt.Image class is actually abstract.

    However, methods such as getImage(URL)

    in the Applet class return an instance of a

    concrete subclass provided by the particular

    JVM im lementation. The details of that

    Handling Image

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    subclass are not important since you invoke

    only methods listed in the Image class, many

    of which are overridden by the subclass.

    The Image class provides only minimal access toinformation about the image. It does include themethods

    int getWidth (ImageObserver)int getHeight (ImageObserver)

    that return the dimensions of an ima e.

    Handling Image Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    You can draw on an image just as you would draw ona component by obtaining the graphics contextobject via the Image class method

    Graphics getGraphics ()

    You then invoke the usual drawing methods in theGraphics object to draw on the image.

    You can create an image just to draw on it using the

    createImage() method from the Component classas in the following snippet:

    Image image = createImage (width, height);

    Handling Image Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Graphics g = image.getGraphics ();

    paint (g); // Your paint() method does the usual drawingoperations

    // but on the image rather than on a component.

  • 8/6/2019 unit-3 New

    41/54

    Threads and Animation

    The only functions we have seen in applets so

    far are init(), paint(), and functions called in

    response to input events. All of these

    Animation

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    of work and return quickly. There has been

    no opportunity, so far, for a function to loop

    and do some continuous work.

    This applet creates a thread, a separate

    stream of execution, to perform a

    background task. The body of the thread's

    code is in the run() function. In this case, the

    Animation Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    variable i once every 1000 milliseconds, and

    cause the applet to redraw itself. The result is

    a simple animation.

    import java.applet.*;

    import java.awt.*;

    public class Threads1 extends Applet implementsRunnable {

    Animation Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    int width, height;

    int i = 0;

    Thread t = null;

    boolean threadSuspended;

  • 8/6/2019 unit-3 New

    42/54

    // Executed when the applet is first created.

    public void init() {

    System.out.println("init(): begin");

    width = getSize().width;

    height = getSize().height;

    setBackground( Color.black );

    " "

    Animation Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    . .

    }

    // Executed when the applet is destroyed.

    public void destroy() {

    System.out.println("destroy()");

    }

    // Executed after the applet is created; and also whenever

    // the browser returns to the page containing the applet.

    public void start() {

    System.out.println("start(): begin");

    if ( t == null ) {

    System.out.println("start(): creating thread");

    =

    Animation Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    System.out.println("start(): starting thread");

    threadSuspended = false;

    t.start();

    }

    else {

    if ( threadSuspended ) {threadSuspended = false;

    System.out.println("start(): notifying thread");

    synchronized( this ) {

    Animation Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    notify();

    }

    }

    }

    System.out.println("start(): end");

    }

  • 8/6/2019 unit-3 New

    43/54

    // Executed whenever the browser leaves the page containing theapplet.

    public void stop() {

    System.out.println("stop(): begin");threadSuspended = true;

    }

    // Executed within the thread that this applet created.

    Animation Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    public void run() {

    System.out.println("run(): begin");

    try {

    while (true) {

    System.out.println("run(): awake");// Here's where the thread does some work

    ++i; // this is shorthand for "i = i+1;"

    if ( i == 10 ) {

    i = 0; }showStatus( "i is " + i );

    // Now the thread checks to see if it should suspend itself

    if ( threadSuspended ) {synchronized( this ) {

    while ( threadSuspended ) {

    System.out.println("run(): waiting");

    wait();

    }

    }

    Animation Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    }

    System.out.println("run(): requesting repaint");

    repaint();

    System.out.println("run(): sleeping");t.sleep( 1000 ); // interval given in milliseconds

    }}

    catch (InterruptedException e) { }

    System.out.println("run(): end");}

    // Executed whenever the applet is asked to redraw

    itself.public void paint( Graphics g ) {

    System.out.println("paint()");

    g.setColor( Color.green );

    Animation Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    g.drawLine( width, height, i * width / 10, 0 );

    }

    }

  • 8/6/2019 unit-3 New

    44/54

    The Java Media Framework API (JMF)

    enables audio, video and other time-based

    media to be added to applications and

    applets built on Java technology. This

    o tional acka e, which can ca ture,

    Sound And Video

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    playback, stream, and transcode multiple

    media formats, extends the Java 2 Platform,

    Standard Edition (J2SE) for multimedia

    developers by providing a powerful toolkit to

    develop scalable, cross-platform technology.

    APPLET

    An Applet is Loaded into a java-enabledprogram (Netscape, Applet Viewer)

    Applet is not a stand-alone program (no mainmethod), structured to run inside anotherprogram (browser)

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    JVM runs applications, but not applets. Anapplet can run as an application if it defines amain().

    Applets are usually event-driven.

    Does I/O through a GUI, only displays error

    messages with stdout. Applets subclass java.applet

    Security - applets barred from reading/writing

    APPLET Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    , ,

    make network connections (except to its

    host), cant execute programs, etc...

  • 8/6/2019 unit-3 New

    45/54

    Applet lifecycle: (methods overridden from

    Applet class):

    init(), start(), paint(g),stop(), destroy()

    Loading an applet

    APPLET Life Cycle

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    an instance of the applets controlling class

    (Applet subclass) created

    applet initializes itself

    applet starts running

    Leaving and returning to applet page

    when page is left, applet stops

    upon page return, applet starts

    Applet reloading/unloading

    APPLET Life Cycle Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    applet performs finalcleanup, before

    reloading

    Browser quitting - (applet stops, performs

    final cleanup)

    Java Bean is a developed by Sun

    Microsystems that defines how Java objectsinteract.

    An object that conforms to this specificationis called a JavaBean, and is similar to an

    Bean

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    ct ve contro .

    It can be used by any application thatunderstands the JavaBeans format.

  • 8/6/2019 unit-3 New

    46/54

    The principal difference between ActiveX

    controls and JavaBeans are that ActiveX

    controls can be developed in any

    programming language but executed only on

    a Windows latform, whereas JavaBeans

    Bean Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    can be developed only in Java, but can run

    on any platform.

    A java bean is a software component that has been

    designed to be reusable in a variety of different

    environment.

    It may perform a simple function , such as checking

    the spelling of a document, or a complex function, .

    Bean Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    A bean may be visible and invisible to end user.

    e.g. Button on a GUI..

    Software to generate a pie chart from a set of data

    points is an example of a Bean that can execute

    locally.

    Advantage

    A software component architecture provides

    standard mechanism to deal with softwarebuilding blocks:

    A bean obtain all the benefits of javas write-

    -

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    , .

    The properties, events, and method of a

    Bean that are exposed to an application

    builder tool can be controlled.

  • 8/6/2019 unit-3 New

    47/54

    Java beans are a framework for creating

    components in Java.

    AWT and Swing packages are built within

    this framework

    Java Beans

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    a e o n w grap c eve opmen

    environments such as Jbuilder and Forte.

    An extension is Java Enterprise Beans

    Code must be written correctly

    Access methods must begin with get

    Mutation methods must begin with set

    Code must support event handling

    Bean Rules

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Objects must be persistent, i.e. implement

    serializable

    Introspection used to asses what a bean can

    do (which methods it has)

    There is also an interface BeanInfo to give

    development tools more information

    Java Beans: Development Environments

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Tools can change a beans properties, e.g.

    background color in a window if the window

    is regarded as a bean.

  • 8/6/2019 unit-3 New

    48/54

    We learned that JavaBeans are Java classes

    which adhere to an extremely simple coding

    convention. All you have to do is to

    implement java.io.Serializable interface, use

    a ublic em t ar ument constructor and

    Summary

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    provide public getter and setter methods to

    get and set the values of private variables

    ( properties ).

    Swing is a widget toolkit for Java. It is part of

    Sun Microsystems' Java Foundation Classes

    (JFC) an API for providing a graphical

    user interface (GUI) for Java programs.

    Swing

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    sophisticated set of GUI components than

    the earlier Abstract Window Toolkit.

    The Java Swing provides the multiple

    platform independent APIs interfaces forinteracting between the users and GUIscomponents. All Java Swing classes importsform the import javax.swing.*; package. Javaprovides an interactive features for design

    Swing Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    t e s too t or components e: a e s,buttons, text boxes, checkboxes, comboboxes, panels and sliders etc. All AWTflexible components can be handled by theJava Swing.

  • 8/6/2019 unit-3 New

    49/54

    The Java Swing supports the plugging

    between the look and feel features. The look

    and feel that means the dramatically

    changing in the component like JFrame,

    JWindow, JDialo etc. for viewin it into the

    Swing Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    several types of window.

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

    Above code sets the operation of close operation to

    Exit the application using the System exit method.

    import javax.swing.*;

    public class Swing_Create_Frame{

    public static void main(String[] args)

    {JFrame frame = new JFrame("Frame in Java Swing");

    Creating a frame by usingSwing

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    . ,

    frame.setVisible(true);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    }

    import javax.swing.JFrame;

    public class Simple extends JFrame{ public Simple()

    { setSize(300, 200);

    setTitle("Simple");

    OR Creating a frame by using Swing

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    se e au ose pera on _ _ ;public static void main(String[] args)

    { Simple simple = new Simple();simple.setVisible(true);

    }

    }

  • 8/6/2019 unit-3 New

    50/54

    Efficient, Convenient, Powerful, Portable, Secure, Inexpensive

    Lightweight threads instead of OS threads created

    Single copy of code brought into memory for all threads

    versus per thread

    Servlet

    Why Java Servlets Instead of CGI?

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Data (session state) can be stored across threads within

    servlet container

    Java is portable and secure

    Requires little expense once servlet container integrated

    with web server

    The advantages of using servlets is their fastperformance and ease of use combined withmore power over traditional CGI. TraditionalCGI scripts written in Java have a number ofdisadvantages when it comes to

    Advantages

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    .a new process is created for each call of theCGI script. This overhead of process creationcan be very system intensive especially

    when the script does relatively fast

    operations (process creation will take more

    time than CGI script execution). Java servletssolve this problem by allowing each requestto be handled by a separate Java threadwithin the Web server process, omittingseparate process forking by the HTTP

    Advantages Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    aemon. n a t on, s mu taneousrequest causes the CGI script to be copiedand loaded into memory as many times asthere are requests. However with servletsthere are same amount of threads as requestbut there will only be one copy of the servletclass created in memory.

  • 8/6/2019 unit-3 New

    51/54

    Java Servlet Objects on Server Side

    Managed by Servlet Container

    Loads/unloads servlets

    Directs requests to servlets

    Servlet Structure

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    Request doGet()

    Each request is run as its own thread

    Web App with Servlets

    GET

    Servlet Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    HEADERS

    BODY

    Servlet

    doGet()

    Servlet Container

    5 Simple Steps for Java Servlets

    1. Subclass off HttpServlet

    2. Override doGet(....) method

    3. HttpServletRequest

    Servlet Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    getParameter("paramName")

    4. HttpServletResponse

    set Content Type

    get PrintWriter

    send text to client via PrintWriter

    5. Don't use instance variables

  • 8/6/2019 unit-3 New

    52/54

    Servlet Creation

    Single instance created

    init() method called

    You can override init() in your subclass of

    Servlet Lifecycle

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    HttpServlet to do some initial code....

    init() is NOT called again on further requests

    On each request, the server spawns a new

    thread and calls service()

    service checks HTTP re uest t e and

    Servlet Cycle Cont.

    (Service Method)

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    calls appropriate doXXXX (Get, Post, Put...)

    don't override service (unless you really

    know what you're doing)

    In this chapter, you learnt about Java events

    and the delegation event model necessaryto support them. More specifically, youlearned about Java events, including theevent listener capable of generating them

    Summary

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    library. You saw examples of using theswings that are more useful in eventhandling and a Java Servlet is an efficient,convenient, powerful, portable, secure,inexpensive thats why it is more useful.

  • 8/6/2019 unit-3 New

    53/54

    Event-driven programming provides the means to

    develop flexible applications where the user

    determines program flow. Implementing event

    handlers in Java is generally straightforward, but it's

    important to know which approach is best for which

    Conclusion

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    . ,

    most common ways to implement event handling:

    dispatching events to an object, using an

    anonymous class to dispatch an event directly to

    the method that handles it, and using reflection to

    write a generic class that dispatches events to the

    event handler method.

    Objective type Questions

    Q1) The CheckboxGroup class is a subclass of the Component

    class.

    (a)True

    (b)False

    -

    Review Questions

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    widths wide and 10 characters height tall.what code do you

    use?

    (a) New TextArea(80,10)

    (b) New TextArea(10,80)

    Q3)Which of the following are direct or indirect subclasses of

    container(a)Frame

    (b)TextArea

    MenuBar

    Review Questions Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    (e)Applet

    Q4)Which method will cause a frame to be displayed

    (a)show()

    (b)setVisible()

    display()

    (d)DisplayFrame()

  • 8/6/2019 unit-3 New

    54/54

    Q5)Which method is method to set the layout of a

    container

    startLayout()

    initLayout()

    layoutContainer()

    Review Questions Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    setLayout()

    Short Questions

    Q1)What is the difference between JDBC and ODBC?

    Q2)What are the types of JDBC Driver Models and explain

    them?-

    Q3)What is source and listener?-

    Review Questions Cont.

    Bharati Vidyapeeths Institute of Computer Applications and Management, Divya Goel, New Delhi-63. #

    -

    Q5)What is meant by controls and what are different types of

    controls in AWT?-

    Q6)What is the difference between choice and list?-

    Q7)What is the difference between scrollbar and scrollpane?Q8)What is an event and what are the models available for

    event handling?

    Long Questions

    Q1)What are the steps involved for making a connection with adatabase or how do you connect to a database?

    Q2)What is the difference between applications and applets?-

    Q3)How are the elements of different layouts organized

    Review Questions Cont.

    over the event-inheritance model?

    Q5)What is a layout manager and what are different types of