Chapter 4-Java Beans

Post on 07-Jul-2018

212 views 0 download

Transcript of Chapter 4-Java Beans

  • 8/19/2019 Chapter 4-Java Beans

    1/11

    Nawaraj Paudel Page 1

    Chapter 4

    JavaBeans

    Introduction JavaBeans are reusable software components for Java that can be manipulated visually in

    a builder tool. JavaBeans components are known as beans. Particularly, they are classeswritten in the Java programming language conforming to a particular convention. sing

    visual application builder tools, software components can be composed into applets,

    applications, servlets, and composite components.Beans are dynamic in that they can be changed or customi!ed. "hrough the design

    mode of a builder tool you can use the Properties window of the bean to customi!e the

     bean and then save #persist$ your beans using visual manipulation. %ou can select a beanfrom the toolbo&, drop it into a form, modify its appearance and behavior, define its

    interaction with other beans, and combine it and other beans into applet, application,

    servlet, or a new bean.

    Reusable Software Components'eusable software components apply the concept of reusable and interchangeable parts to

    the field of software construction. 'eusable software components can be simple, such as buttons, te&t fields, list bo&es, scrollbars, and dialogs. 'eusable components add

    standardi!ed interfaces and object introspection mechanisms to widgets, allowing builder 

    tools to (uery components about their properties and behavior. )eep in mind, too, that

    software component need not be visible in a running program* they only need to bevisible when the application is constructed. + programmer can move, (uery, or visually

    hook together components while operating a builder tool. ften, such components do

    their work while the program is running, though they are invisible to the user.

    %ou can purchase custom JavaBean components from third party vendors. %ou canalso purchase builder tools or application construction programs that support JavaBeans.

    +pplication construction tools let you build Java applications using the mouse as your  primary input mechanism. %ou select components #from pallets, panels, or menus$ and

    drop them into a form, or client window. %ou can change the behavior and look of these

    components by editing their properties, and you can link the actions of one component to

    another via events and event handlers.Components can be nested and arbitrarily comple&. -or e&ample, a calculator built

    from components becomes, itself, a component to another application. Custombuilt

    components are easily added to builder tool palettes.

    What Distinguishes JavaBeans from Java Classes?+ny Java class that adheres to certain conventions regarding property and event interfacedefinitions can be a JavaBean. Beans are Java classes that can be manipulated in a visual

     builder tool and composed into programs.

    Introspection, the process by which a builder tool analy!es how a Bean works,

    differentiates Beans from typical Java classes. Because Beans are coded with predefined

    Advanced Programming Techniques

  • 8/19/2019 Chapter 4-Java Beans

    2/11

    Nawaraj Paudel Page 2

     patterns for their method signatures and class definitions, tools that recogni!e these

     patterns can /look inside/ a Bean and determine its properties and behavior.

    Introspection allows a Bean0s state to be manipulated at design time 1 that is, at thetime it is being assembled as a part within a larger program. -or this to work, method

    signatures within Beans must follow a certain pattern so that introspection tools recogni!e

    how Beans can be manipulated, both at design time and at run time.In effect, Beans publish their attributes and behaviors through special method

    signature patterns that are recogni!ed by beansaware application construction tools.

    2owever, these construction tools are not re(uired to build or test your beans. "he patternsignatures are easily recogni!ed by human readers, as well as builder tools. ne of the

    first things you0ll learn when building beans is how to recogni!e and construct methods

    that adhere to these patterns.

    Basic Bean Concepts+ Java Bean is a reusable software component that can be visually manipulated in builder 

    tools. JavaBeans, regardless of their functionality, are defined by the following features.

    •Introspection:  Beans support introspection, which allows a builder tool toanaly!e how Beans work. "hey adhere to specific rules called design patterns for 

    naming Bean features. 3ach Bean has a related Bean information class, which

     provides property, method, and event information about the Bean itself. 3achBean information class implements a BeanInfo interface, which e&plicitly lists

    the Bean features that are to be e&posed to application builder tools.

    • roperties: Properties control a Bean0s appearance and behavior. Builder tools

    introspect on a Bean to discover its properties and to e&pose them for 

    manipulation. +s a result, you can change a Bean0s property at design time.

    • Customi!ation: "he e&posed properties of a Bean can be customi!ed at design

    time. Customi!ation allows a user to alter the appearance and behavior of a Bean.

    Beans support customi!ation by using property editors or by using special,sophisticated Bean customi!ers.

    • "vents: Beans use events to communicate with other Beans. Beans may fire

    events, which mean the Bean sends an event to another Bean. hen a Bean fires

    an event it is considered a source Bean. + Bean may receive an event, in which

    case it is considered a listener Bean. + listener Bean registers its interest in theevent with the source Bean. Builder tools use introspection to determine those

    events that a Bean sends and those events that it receives.

    • ersistence: Beans use Java ob5ect seriali!ation, implementing the

    java.io.Serializable  interface, to save and restore state that may have

    changed as a result of customi!ation. 6tate is saved, for e&ample, when you

    customi!e a Bean in an application builder, so that the changed properties can berestored at a later time.

    • #ethods: +ll JavaBean methods are identical to methods of other Java classes.

    Bean methods can be called by other Beans or via scripting languages. +

    JavaBean public method is e&ported by default.

    Advanced Programming Techniques

  • 8/19/2019 Chapter 4-Java Beans

    3/11

    Nawaraj Paudel Page 3

    hile Beans are intended to be used primarily with builder tools, they need not be. Beans

    can be manually manipulated by te&t tools through programmatic interfaces.

    Bean 7evelopment )it #B7)$ and Bean Bo&B7) is delivered separately from the J7). %ou can download it from the JavaBeans web

    site and use it. "he BeanBo& is a simple tool you can use to test your Beans, and to learnhow to visually manipulate their properties and events. "he BeanBo& is not a builder tool.%ou0ll use the BeanBo& to learn about Beans. %ou can create a JavaBean and then use the

    BeanBo& to test that it runs properly. If a JavaBean runs properly in the BeanBo&, you

    can be sure that it works properly with other commercial builder tools.

    Starting the BeanBo$hen you start the BeanBo&, you0ll see three windows8

    • %oolBo$ window

    • BeanBo$ window

    • roperties window

    %he %oolBo$ window displays the JavaBeans that are currently installed in the BeanBo&,

    such as the Beans they come with the BeanBo& demo. hen the BeanBo& starts, itautomatically loads its "oolBo& with the Beans in the J+' files contained in the bean95ars

    directory. %ou can add additional Beans, such as your own Beans, to the "oolBo&.

    %he BeanBo$ window  itself appears initially as an empty window. %ou use thisempty window, sometimes referred to as a /form/ by other builder tools, for buildingapplications.

    %he roperties window displays the current properties for the selected Bean. If no

    Bean is selected, such as when you first start the BeanBo& or if you click in the BeanBo&window0s background, then the Properties window displays the BeanBo& properties. %ou

    can use the Properties window or sheet to edit a Bean0s properties.

    Advanced Programming Techniques

  • 8/19/2019 Chapter 4-Java Beans

    4/11

    Nawaraj Paudel Page 4

    &sing the BD' BeanBo$"he easiest way to understand how the BeanBo& works is to use it. "he BeanBo& enablesyou to construct simple Beans applications without writing any Java code. +s a first

    e&ample, you can build a simple /Juggling 7uke/ application in which 7uke will start or 

    stop 5uggling depending on which of two buttons you push. In this lesson, you0ll learn

    how to8• 7rop Beans from the "oolBo& into the BeanBo& and change their properties using

    the Properties sheet and associated property editors.

    • 2ave one Bean fire an event and another Bean react to the fired event.

    Creating (our Beane0ll start by dropping the Juggler Bean from the "oolBo& into an empty BeanBo&.

    :. Click on Juggler Bean to select from the list of Beans in the "oolbo& window.

     ;otice that the cursor changes to a crosshair.. se the BeanBo& 3dit menu to select an action event to be fired by the start

     button. Before choosing the event action, be sure that you have selected the start button.

     ;otice that once you select the actionPerformed menu item, BeanBo& enters a statewhere a line emanates from the start button and follows the mouse as you move it around

    the window. "his indicates that the button is the selected source for the action event, and

    that your ne&t mouse press should be over the target Bean which defines appropriateeventhandler methods, in this case the Juggler Bean.

    ?. 7rag the line from the start button and release it over the Juggler Bean. + dialog

    appears listing applicable event handlers defined by the Juggler Bean.

    @. 6elect the startJuggling method as the target for the event, then press ).

     ;ow, when you press the start button 7uke should start tossing beans around in a

    circle over his head like a professional 5uggler.%ou can control 7uke0s 5uggling speed by manually setting the property value labeled

    animation'ate in the Juggler0s property sheet editor. -or the appropriate property sheet

    editor to appear, the Juggler must be the currently selected Bean within the BeanBo&

    frame.

    Completing (our rogram

    Advanced Programming Techniques

  • 8/19/2019 Chapter 4-Java Beans

    5/11

  • 8/19/2019 Chapter 4-Java Beans

    6/11

    Nawaraj Paudel Page 6

    ser must create the manifest file to provide which components in the J+' file are 5ava

     beans. %ou can put any number of files in the manifest file entry but if you have class

    files acting as 5ava beans then each entry of the file must be immediately followed by theline Java.Bean: %rue-or e&ample,

    ame) SimpleBean.classava+Bean) ,rue

     ;ame the file as SimpleBean/mft #or .tmp or of your choice$

    2ere if you have other resources you can append them using ;ame8 resource path. hileincluding class name if you have created package write full path including package. "he

    above file indicates that there is only one class file in J+' file.

    0enerate a J1R file

     5ar cfm 6impleBean.5ar 6impleBean.mft 6impleBean.classther three steps are as done previously.

    Introspection"he introspection services provided by the JavaBeans +PI are divided into two parts8low.level services and high.level services. "he lowlevel +PI services are typically used by application builder tools, which make heavy use of bean internals to provide advanced

    development features. "his level of access isn0t appropriate for application developers,

    however, because it e&poses bean internals that aren0t meant to be accessible at theapplication level. -or developers, the highlevel +PI services are more appropriate. "he

    highlevel services provide access to a limited portion of a bean0s internals, which

    typically consist of a bean0s public properties, methods, and events. "he highlevelintrospection services rely heavily on the lowlevel services* the primary difference

     between the two is that the highlevel services limit access to bean internals.

    "here are two approaches to introspect. "he automatic approach  to introspection

     provides bean information automatically. -or those cases in which bean developers wantto get up close and personal with bean information, there is an e$plicit approach.

    "he first approach of JavaBeans automatically assessing information about a bean

    uses the reflection facilities in the core Java +PI. "he reflection facilities are responsiblefor analy!ing the lowlevel structure of a bean and returning information. "he

    introspection facilities in the JavaBeans +PI take this information and apply design

     patterns to it to determine the specifics about the public properties, methods, and eventssupported by a bean.

    "he e&plicit approach to defining bean information re(uires a little more work on the

     part of bean developers. "he JavaBeans +PI provides support classes that are used by

    developers to e&plicitly define the public information for a bean. )eep in mind that this

    approach is purely optional and can even be used in combination with the automaticapproach. In other words, developers are free to e&plicitly provide some bean information

    and allow the introspection facilities to automatically determine the rest. It0s important tonote that automatic introspection is the default approach taken by JavaBeans, and is

    superseded only if e&plicit information is available. "his ability to leverage both

    introspection approaches provides lots of fle&ibility for bean developers.

    Advanced Programming Techniques

  • 8/19/2019 Chapter 4-Java Beans

    7/11

    Nawaraj Paudel Page 7

    7esign PatternsBean developers are not re(uired to add any additional support for introspection in their code. "hey only have to structure the code for the bean itself because JavaBeans relies on

    the naming and type signatures of the methods defined in the code for a bean to

    determine what properties, methods, and events the bean supports for public use. In other words, the conventions used in the code for a bean are also used as a means to introspect

    the bean.

    "he automatic approach to JavaBeans introspection relies heavily on the naming

    conventions and type signatures of a bean0s methods, including methods for registeringevent listeners. "he approach relies on design patterns, which are standardi!ed naming

    conventions and type signatures that are used to define bean methods based on their 

    function."here are a variety of different design patterns for specifying everything from simple

     properties to event sources. +ll of these design patterns rely on some type of consistent

    naming convention for methods and their related arguments and types. )eep in mind thatthis approach to introspection is not only convenient from the perspective of JavaBeans,

     but it also has the intended side effect of encouraging bean developers to use a consistentset of naming conventions. 2ere are the three ma5or types of design patterns, each of 

    which are discussed.

    • ropert( design patterns

    • "vent design patterns

    • #ethod design patterns

    ropert( Design atternsProperties are private  values accessed through accessor  methods # getter   and setter 

    methods$. Property getter and setter method names follow specific rules, called design

     patterns. "hese methods are used to identify the publicly accessible properties of a bean.

    It turns out that accessor methods are the means by which the JavaBeans automatic

    introspection facilities determine which properties a bean e&poses. Basically, any time theJavaBeans introspector encounters a public getter or setter method, it assumes the

     property in (uestion is a public property and e&poses it to the outside world.

    Properties need not always have pairs of accessor methods. -or e&ample, if a propertyhas only a getter method, JavaBeans assumes it is a readonly property. ikewise, if a

     property has only a setter method, JavaBeans assumes it is a writeonly property. If both

    methods are defined it is a readwrite property. +s you can see, design patterns areama!ingly simple, but (uite effective. "he design patterns for properties vary a little

     based on the type of property.

    2/ Simple ropert(6imple properties consist of all singlevalued properties, which include all builtinJava data types as well as classes and interfaces. -or e&ample, int, lon&, float,

    Color, -ont, and boolean  are all considered simple properties. "he design

     patterns for simple property accessor #getters and setters$ methods follow8

    public /ropert0,0pe1 &et/ropert0ame1(

    Advanced Programming Techniques

  • 8/19/2019 Chapter 4-Java Beans

    8/11

    Nawaraj Paudel Page 8

    public void set/ropert0ame1(/ropert0,0pe1 x

    6o, for a property called color that is of type Color, the following accessor 

    methods would safely conform to the introspection design patterns8

    public Color &etColor(

    public void setColor(Color c

    hen the JavaBeans automatic introspector encounters these method definitions,

    it determines both the color public property, as well as the &etColor( and

    setColor( accessor methods for accessing the property. +nd this takes place

    without you having to do anything more than conform to the simple property

    design patterns when you design your methods. -or e&ample,

    import java.awt.*;

    import java.io.*;

    public class SimpleBean extends Canvas implements

    Serializable {

    private Color color 2 Color.&reen;

    public Color &etColor({

      return color;

      '

    public void setColor(Color newColor{

      color 2 newColor;

      repaint(;

      '

      public void paint(3rap4ics & {

      &.setColor(color;

      &.fill5ect(6"# 7# 6"# 8";

      '

      public SimpleBean({  setSize(!"#$";

      setBac%&round(Color.red;

      '

    '

    3/ Boolean ropert(Boolean Properties are technically simple properties of boolean  type. "hey

    have an optional design pattern for the getter method that can be used to make it

    more clear that a property is of boolean type. "his design pattern follows8

    public boolean is/ropert0ame1( 99preferred one

    public boolean &et/ropert0ame1(

    "he only difference between this design pattern and the one for simple properties

    is that it uses the word is  instead of &et in the name. It is fairly common for 

    Java developers to access boolean properties with an is method, which is why

    JavaBeans supports the use of this special case design pattern. "he following is an

    Advanced Programming Techniques

  • 8/19/2019 Chapter 4-Java Beans

    9/11

    Nawaraj Paudel Page

    e&ample of a pair of accessor methods for a boolean  property named

    amp4ibious that conforms to the boolean design pattern8

     public boolean isAmphibious()

     public void setAmphibious(boolean a)

    %ou might be wondering what happens in the event that both a &et method andan is method are defined for a property. ;ot to worry, JavaBeans handles this by

    always using the is method if it is available, and the &et method if not.

    4/ Inde$ed ropert(+n inde&ed property is an array of simple properties. Because inde&ed properties

    re(uire slightly different accessor methods, it only makes sense that their design

     patterns differ a little from other properties. 2ere are the design patterns for inde&ed properties8

    //Methods to access individual valuespublic get(int index);

    public void set(int index value);

    //Methods to access the entire indexed property arraypublic !" get();public void set(!" value);

    "he first pair of design patterns defines accessor methods for getting and setting

    individual elements in an inde&ed property. "he second pair of patterns definesaccessor methods for getting and setting the entire property array as a whole. -or 

    e&ample,

     public Color getPalette(int i);

     public void setPalette(int i, Color c); public Color[] getPalette();

     public void setPalette(Color[] c);

    In this e&ample, the inde&ed property is called palette  and is an array of 

    Color ob5ects. "he first pair of accessor methods enable you to get and set

    individual colors in the palette, and the second pair enables you to get and set the

    whole palette of colors.

    Advanced Programming Techniques

  • 8/19/2019 Chapter 4-Java Beans

    10/11

    Nawaraj Paudel Page 1!

    "vent Design atternshen a bean0s internal state changes, it often is necessary to notify an outside party of thechange. "o accomplish this, beans are capable of broadcasting event notifications that

    inform interested parties of some change in a bean. 3vents themselves can represent

    many different types of notifications, but some of the most popular ones are mouse clicks

    and drags. -or e&ample, when the user drags the mouse over a bean, you might want the bean to notify its parent so the appearance of the cursor can be changed. "his notification

    is handled by the bean sending its parent an event. Beans send notifications to eventlisteners that have registered themselves with a bean as wanting to receive event

    notifications. Because listeners must register themselves with a bean, it is important that

     beans provide appropriate methods to facilitate the registration process. "he eventregistration methods come in pairs, with one method enabling listeners to be added and

    the other enabling beans to be removed. Because this method pair is sufficient for 

    defining an event registration between a bean and an interested party, it0s probably not

    going to come as a surprise to you that the JavaBeans introspector uses these methods toassess the events that a bean is capable of sending.

    3vent registration methods must conform to the following design patterns for theautomatic introspection services to work properly8

    public void add:ventistener,0pe1(:ventistener,0pe1 x;

    public void remove:ventistener,0pe1(:ventistener,0pe1 x;

    In these design patterns, E3ventistener"ypeF refers to the ob5ect type of the event

    listener being registered with the bean. JavaBeans re(uires that thisob5ect implement the :ventistener  interface and have its name end with

    istener. "herefore, if you want to add support for an event listener implementing the

  • 8/19/2019 Chapter 4-Java Beans

    11/11

    Nawaraj Paudel Page 11

     public void addActionListener(ActionListener al) throws

    Tooan!Listeners;

    public void remove