You are on page 1of 20
In Depth Java Beans are Sun's ang ee wer written in to Mi scoala Beatie : mming environment controls, methods, and events to ce of serum Beans are reusable code components controls” such rk much pen ehvironments, including third-party ‘col as buttons thar ra mPonents, Yar lke Activex controls, eae properties, information from the Intemnes, ©Olors Wher aud Peete vouicin’ ciewisyors Gun new lave Java Beans is designed to be coun ™ click them or stock tickers that download that let you configure beans in ion Ba (BDK), which you can downloa nee tool, the Cuilder tools, w construct and use beans, represent a powerful new way usable code ent J2¥8-8uin-com Wola BDK in this chapter to /AY of looki, 'Ponents that you ca ae pon. ing at Programen You can create applications from, beans sents by addin, ERB You can create your own applications on the What you ys ppl ae need —and nothing more. build Nas Plea this Part is very important. The reason for Upplied by Sa S¥Stems from software components. These Pecifies how th, ‘y One or more different vendors. Actually, Java Beans If you want to understand th ® Pallding blocks can operate together, the construction of a system, hardin neats nora better way, then consider the following example. In variety of components weene's Perform a very important function teinging wide eee cme oe to construct a system, The Geaesibee simple building Bees tare All of these different parts ae More advanced functionality is provided by the integrated circuits. Zeused. It is not necessary or possible to rebuitd these capabilities each in different types of circuits the same pieces can be used. This is time a new system is needed. Moreover, possible only because the behavior of these components is understood and documented. ity and interoperability of a The software industry has also been seeking the benefits of reusabilit component-based approach. Component architecture is needed that allows | ‘hich are programming, environments install from nes “© comes with the Sun Bean Development Kit allow. components may be provided by os soos) defines an architecture that s See it must be easy to incorporate this functionality into existing code. Fortunately, such architecture is provided by Java Beans. : Sun supports Java Beans in the java.beans package, Here's an overview of the interfaces in that package: Q AppletInitializer—It imitializes applets and is designed to work with java.beans.Beans. instantiate. i ; Q BeanInfo—This interface provides explicit information about the methods, properties, events, and ) wae see customizer class provides a complete custom GUI for customizing a target Java Bean. 7 | DesignMode—This interface is java.beans.BeanContext in designTime property. be implemented by or delegated from instances of intend delermine whether a bean is under design using the 1275 }: Work Java Beans Chapter 28: cing with Ja ee ‘ “ng et yChi Q propertychangebistener—It handles Prope: ers to edit a proper property. A It provides support for GUIs that allow us Property value u PropertyEditor— s events that are fired when a bean changes a Sorry given type. VetoableChangeListener—It handles : af ircumstances a be: pro) ether a bean is visible (under some ch 20 My ben Q visibility—It indicates whethe on servers where a GUI is not available). i i beans: res an overview of the classes in java - , de i ides global information about a bean, including its Java class, its nay, BeanDescriptor-It provides glol : control methods. a and so on. Q_Beans—It provides some general-purpose bean ; : EventSetDescriptor=lt describes a group of events that a given Java Bean fires, for PropertyDescripto, Q FeatureDescriptor—The common base _class EventSetDescriptor, and MethodDescriptor. f Q IndexedPropertyDescriptor—It describes a property that acts like an array. ; Introspector—It provides a standard way for tools to learn about the properties, events, ang methods supported by a Java Bean. MethodDescriptor—It describes a particular method that a Java Bean supports for extemal a access from other components. Q ParameterDescriptor—It provides information on each of a method’s parameters, beyond the low-level information provided by the java. lang. reflect .Method class. Q PropertyChangeEvent —It listens for PropertyChange events that are fired when a bean changes a bound or constrained property. Q PropertyChangeSupport—A utility class that can be used by beans that support bound properties. E Q PropertyDescriptor—It describes one property that a Java Bean exports. Q PropertyEditorManager—It can be used to locate a Property editor for any given type name. a PropertyEditorSupport —A support class that helps build property editors. J simpleBeanInfo~A class that makes it easier for users to provide BeanIn£o data. 1 _VetoableChangeSupport—A utility class that can be used by beans that support constrained ia novo mp wsaeh saedsed Ent evs” properties. n this chapter, we'll create a number nd methods and let users embed « of Java Beans—from simple ones to ones that support properties ‘inside them. Ippo! what IS. Java Bean? Bean is a software co AJava Bean § ™Ponent. Thy, erent environments. Regardin is i cite of function, ie, simpic ce Wel ease has inventory value, and in complex function MPI In ean {a Bean may be Visible to an end yarn function examples are obtaining, an ‘A Bean may also be visible to q ting the as Performance of a stock portfolio. ! : Isa butts stock p siream of multimedia information in see sa™ Pe of or Lanna phil se inerace on a user's workstation or 2 nates {YP OF by te . ime. Finaly uilding block is wi decode a ple of Bean that can nea tpn abn may we eek star deo, 2 orints. However, it is Necessary that ly ithe sofwwat that ee Other distributed components. An Emmodities exchange would need sc Rein which provides ites eae oe ost of data dnt Te ey Bean conepis arr gens OrPran wie i eran fom ook a. Firstly the builder tools discover 4 e process known as introspection Beay nigitsisned to be reusable in a variety of Ro Festriction. It can perform different are fo Simple pcs 4s, its properties, methods, and events) by a ection in two ways: rules, ss class Telies on th Teflection, = ety Providing property, method, and event information with a pt dies, 4 Bean information class implements the BeanInfo application builder tools, ‘xplicitly lists those Bean features that are to be exposed to 2. Properties are the Bean's appearance and behavior time. Builder tools introspect on a Bean to dissove manipulation. known as design patterns, at the time when ‘examines Beans for these design patterns to Core reflection API. The Reflection API is an It provides support by related Bean Information characteristics, which can be changed at design its properties, and expose those properties for Qo Beans expose properties so that, they can be customized at design time. In this case, customization is supported in two ways—using property editors by using more sophisticated Bean customizers. Q Beans use events in order to communicate with other Beans. A Bean that wants to receive events (i.e. a listener Bean) registers its interest with the Bean that fires the event (i.e. a source Bean). Builder tools can examine a Bean and determine which events the Bean can fire (send) and the one that it can handle (receive). /Persis bl Beane’ ton aevyelmnd fentore! ter aia) Once you have’ chang We" Beans eae vaca ve the state of the Bean and restore that Bean at a later time. Remember that, Be hes eres Java Beans uses Java Object Serialization to support persistence. OA Bean's methods are similar to the methods of Java methods. This method can be called from other Beans or a scripting environment. By default all public methods are exported. rien rer for y b stood by builder tools, all key APIs, including, suppor Although Beans are designed to be understood by b ‘to be easily read as well as understood by events, properties, and persistence, have been designed to the Java platform by the Java Beans. You sh ponent ‘with the Java Beans API. You can combine these ‘builder tools, into applets, applications, or Sa 1277 _Ghapter 28: Working with Java Boars" \ | Advantage of Java Beans roe Some of the benefits that JavaBean tecing,,, | i n ‘The Java Bean technology plays 4 very dmparian ee provides for a component developer are: vere” paradigm are es a [All the benefits of Java’s “writeoncer run-anyw! is another application, such ‘i a ee methods of Bean that are ExPORCH ora Q The properties, event builder tool, can be controlled. To help configure a Bean, auxiliary software the Bee analpsramctes for that component not need to be included. i” 2 Im the persistent storage, the configuration settings 0! time. You can also use Bean to register the receive & sent to other objects. Introspection Introspection is present at the core of Java Beans. You can define to determine its capabilities. As it allows another application, such about a component, therefore, it is an essential feature of the Java _cannot operate without introspection. (There are two ways by which the developer of a Bean can indicate which of its properties, events, and ‘methods should be exposed by an application builder tool. The simple naming conventions are used with the first method. These allow the introspection mechanisms to infer information about a Bean. Ina second way, an additional class that extends the BeanTnfo interface is provided that explicitly supplies this information. Customizers (The role of the customizer, which is provided by a Bean developer, is to help another developer configure the Bean. A customizer can provide a step-by-step guide through the process that must be followed to use the component in a specific context. Online documentation can also be provided. To eee led. This software is only needed vw can be provided ne run-time environment, i a \ t are being set. In Bean can be saved and restored at a late sents from other objects and generate events that are this as the process of analyzing a Bean a design tool, to obtain information Bean API. The Java Bean technology ci tena fect brs peggy 0) eaitsaltine? smpiC * ines wes Goria aE AbD ait 2 = ctipoonpe a ets ARaTRE il lip He Hla Jmmedaiate gnderstanding Java Be The Novice programmer ap; jaa Bean and its relation a Ad say and how these processes function «°°: Moreoy, User of quite simply. You need not worry ay Pele Tenet they ask et ems to be a mat eR, Ne” Sin Sto be a little these can be manipulated in a yj . Bece requirement of the user. There sual builder tog] 8° @ Java lescribed are certai, too] Be ertain oth can be ‘a Java Bean can be any Java cl ler adv, £01 Sa lass th antag. ir interface definitions. Beans are that adheres to re * with regard ‘oie, you sre ation as per the 1 + you say, sed into applicati Java cla ain, t composed into applications, SS€5 that can be many ntiOns Fegarding Introspection is the process by whi mnipulated ina view! toaloee et sine from the typical Java ees" ® builder too eee lasses, anal signatures and class. definitions, Toi Beans ae a how a Bean im lat i: Predefir determine its properties and behavior, lese patterns i : can “look inside” a Bean and Designing Programs using Java Beans “So how do I use Java Beans anyway?” the Novi application builder tools,” you ey een Be racy omatmmne: Wants f now. -You use them in ow aaeeNoe % tool that comes with the Bean Development After you have downloaded and installed the Bean Development Kit (BDK), which is currently at c e suming that you have installed the BDK (the on path varies by system), you can open the beanbox; for example, in Windows, you use the run.bat ein the beanbox directory. When you run this batch file, the beanbox opens, as shown in Figure 23.1 You can see the available beans in the toolbox on the Jeft. When you add beans to an application, they'll appear in the beanbox window next to the toolbox. You can also use the Properties window to set the Proves Heck Fe el ll ere ttn rl you ean ce a et Toe See ed method execution, Here's an’ example ehowing how t0 Work with some beans. - Click the Juggler bean in the toolbox, which changes your cursor fe 8 ee seine cole aa Jageler bean inthe tot ane (hs bean plays ths ee oo om onde design oust x by dragging om This result in the application wer = bet), Dacha eae Fee eam UTES aE creat sgl aplication 20VS Ag a a ec SD bem when ms ee tnen . For example, you can connect the button Nggler will stop juggling. . 1279 Figure 28.2: Creating an application. ‘Firs, click the buiton bean in the beanbox. The Properties window will display the properties ‘set fortis bean, including is label—if you want to enter a new label for this button (such 2 ‘Me’), you can do it inthe Properties window (you'll see how to set the properties of your own b vay lt), To mae the button do somthing when you cick alec he Est | Evens | {ctionPerformed mena item nov. When you do, are line appears between the mouse locator button, Stretch tat ine othe Juggler bean now and click the Juggler bean, as shown in Figure connects the button and theJugglerbean re SCE That's all there is to it. Now when you click the bu Congratulations, you have connected two beans, How do you actually run this program ton in the beanbox, the juggler will stop juggling. thus creating a new program. Outside the beanbox? Take a look at the next solution. ‘Figure 28.4: The EventTarget dialog box. i ii aii tases i ‘ans Creating Applets that use Java Beal plenty of beans in it and I want to “Ok says the Novice P v thar Seate a JAR file that I can at Si ! ” "you say. “Maybe,” the NP says, storing files in a JAR file with the this case, we are creating an applet that applet including the Chapter 28: Working with Java Beans import java.awt.*; import Java appiet.Applet: /* ' */ nae blic class applett extends et . s peel Sei volibsinetoraihics q)

jar cf applett.jar applett.class ; e i the Fik ‘After you have designed an applet using the beanbox, you can use the MakeApplet item in the File menu to create a JAR file containing your new applet and all the beans it uses. When you select this menu item, it opens the Make an Applet dialog box you see in Figure 28.5. Figure 28.5: The Make an Applet dialog box. In this example, we'll use the applet we developed in the previous solution. We'll stick to the default JAR file name, myApplet . jar, and applet class, MyApplet. When we click OK, the myApplet . jar file is created. a. If you want to use any of the beans that come with the BDK in an applet JAR file, you'll have to compile them first and make sure the java compiler can find their class files. You'll find those beans in the demo\sunw\demo directory. In addition, you'll need to compile the AppletSupport . java file in the beanbox\sunw\beanbox directory and make sure the java compiler can find the resulting class files. The myApplet . jar file can be used with Web browsers and the Sun appletviewer (see the solution “Letting Applets Get from JAR Files,” earlier in the chapter, for more information). Here's the HIML page, we'll use let ‘eve Immediate Solutions , running the code you can see the Ae lets. ating a Java Bean cre ice Programmer appears and says. « The peans?” “Well,” you say, its mot foo ae Hed Java ey fo se a sionple Java Beat in thy, co ety Ooms he 2 nee BOW do I actually create Well Sipe rest ofthe chapter. This bean wig’ © SHOW how beara ae Uboh. says the NP. ofthe number of times its been clicked) ™™ iSelf in red, anek neat Well elaborate on this N | len you click it, it'll display a “place this bean in the BDK's q ; ef \sunw\demo\Bean—and store the class a by indicating that this bean is part of Applet in SNS ®Ppletiewer, Now you law TALI YOU, w how to use Java eno fen Ja¥% kage sunw.demo. bean; import java.awt.*; import java.awt.event.*; {star as the actual bean class goes, we use the Canvas class to dra i sie clases, such as the Panel class, which we'll do in this eee oe ordinary; we just add a mouse listener to the canvas to record mouse clicks, and we set the ee canvas (thus setting the size of the bean): ss package sunw.demo.bean; import java.awt. import java.awt.event.*; public class bean extends Canvas { int count; public bean() { addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { clicked(); } Rint = 0; setsiz(200, 100); } ae bs oa = = lied. taal i = ‘fs the bean, including the click Swipe ha med teh Beery me eee tne * 1283 Chapter 28: Working with Jai useAdapter() { See fed(wouseEvent me) { clicked(): ) public void mousePresst Rint = 0; setSize(200, 100); - Public void clicked() (counts: repaint(): } iblic void paint(Graphics g ree Dimension dimension = getsizeQ): int height = dimension.height; int width = dimension.width; g.setColor (new Color(255, 0. 0)): g.fillRect(0, 0, --width, --height); g.setColor(new Color (0. 0, 0)): Q.drawString("Ct ick count = " + count, 50, 50); } 2 This example is bean. java on the CD. As you can see, the code for a new Java Bean is pretty simple— essentially, you just draw a component. However, it's not a bean yet—we still have to put it into a JAR file and label it in that JAR file as a bean. To learn more about how this works, see the next solution. Creating a Bean Manifest File The Novice Programmer appears and says, “Well, I have written the code for my new Java Bean, but now what?” You smile and say, “You have to pack the bean into a JAR file and indicate that it’s a bean in the JAR file’s manifest file.” “Tell me more!” says the NP. To make a bean into a bean, you have to store the class file(s) to use in a JAR file, and you use a manifest to indicate which classes are beans. To show you how this works, we'll use the bean we started developing in the previous solution and create a manifest file, bean m£t, for it here. We'll place this manifest file in the demo directory to make creating the JAR file easier (see the next solution). To indicate that a class in a JAR file is a Java Bean, you have to set its Java-Bean attribute to True. Here’s how that works with the bean introduced in the previous solution—bean .class. This class file is in the sunw.demo.bean package, which means it'll be stored in the JAR file as ‘sunw/demo/bean/bean.class (like Unix, JAR files use forward slashes as directory separators). To indicate that this class file is a bean, here’s what we put in the manifest file, bean.mf£t: Name: sunw/demo/bean/bean.class ryebAsc Redbatt tasts bes got the class files for my new bean, and I have ° ou are ready to use the jar tool.” “You over the previous tw‘ s; bean.class an manifest file developed in the ee ae he Previous so) i . Make sure you are in thy solu mediate Solutions wedy (05° e demo dipatot Be an. FY and neat Nt the de "mo directory. Now we are q ¢:\.--\demo>jar cfm -Niars\bean) Jartool, like this, 2” N° Jar bea oe eee ee Fuscrentes the new JAR file for this bean, bea, unw\demo\bean\* class ‘here the beanbox will look for it, That's he nd stores is wey. The ne bean i rey f hm the demo\ jars directory, which Work in theneatiat Placing its JAR file in that BO, and it's put eo oe install a bea jsing a New Bean have developed a new Java Bean over i We jory. When you open the beanbos, aan ples de toolbox. You can draw a bean of thi ns qhis new bean is already active in umber of times it’s been clicked. This nese asadding other Java controls to it? Take a look at the by Clicking it, because it shows th aes ‘ ows the Java Bean is a 800d start, but what about doing more, such Next solution, fae ee a Se EE EEE eee Adding Controls to Beans “{don’t want to have to reinvent the wheel,” ask. “Well, it means that if I want a button in myself—why can’t I just use a standard Java can?” You can add Java controls such as buttons to your beans—you just have to make sure you base your bean on a class that’s a container, such as the Panel class. Here’s an example in which we add a button toa bean and have the bean display the number of times it has been clicked. We start by basing this bean, which we'll call “button,” on the Panel class and adding it to the sunw.demo.button package (which means we'll store its class files in the demo\sunw/\ button directory). Here’s how we create the panel, size it, and add a button to it: Says the Novice Programmer. “Which means what?” you my new Java Bean, why do I have to draw and support it button?” “OF course you can,” you say. The NP asks, “You package sunw.demo..button; import java.awt.*; import java.awt.event.*; ActionListener { extends Pane! implements public class button extend eo the click count when the button is e paint method: 1285 eer eee ng a package sunw.demo.button: import java.awt. import java.awt.event.*7 publ ig class button extends Pane! implements ActionListener ( int count; Button buttont: public button() { count = 0; setSize(200, 100); button1 = new Button("Click me"): button1 .addAct ionListener (this) : add(button1); } void actionPerformed(ActionEvent e) { count++: repaint): } public void paint (Graphics 9) { Dimension dimension = getSize(); int h = dimension.height; int w = dimension.width; g-setColor(new Color(255, 0, 0)); g.fillRect(O, 0, w-1, h-1); g.setColor(new Color(0, 0, 0)); g.drawString("Click count = " + count, 50, 50); } public + ‘The example appears on the CD as button. java and button.mft. As you can see, it’s easy to add Java controls to a bean. Giving a Bean Properties “I notice,” the Novice Programmer says, “that you can set the properties of a bean in the beanbox using the Properties window. Why can’t I do that with the beans I create?” “You certainly can,” you say. The NP says, “Wow!” The properties of a bean let you configure it, setting its caption, size, color, and any other aspect of the bean for which properties are defined. Although, any public data member of a bean class can be treated as a property, there’s a formal procedure you should follow to inform the Java framework about the properties of your beans: implementing the BeanInfo interface. The fields of the BeanInfo interfac appear in Table 28.1 and its methods in Table 28.2. Ini tnd = sireme hui tee) Table 28.1: Fields of the Beaninfo interface Itind: lic PSA e icon 732: Methods of the Beaninfo intara ce o jonalBeanInfo() £0 eral it allows a, eee eaNInto obj Hection of other Bean eno to return an arbitrary © objects It Sets the bean's bean, descriptor peat gota sscriptor BrseanDesce 1ptor () It gets the efi (the event that ui ¢¥ent A bean may have a default Will mostly commonly be used) ee Tt gets th cee cet Property index. A bean may have a Renta ieee te ey that will mostly commonly devefaultBvent Index () prentsetbescriptor[] 5 geteventSetDescriptors () Jnage geticon Tt sees gets an image obj (int iconKind) besia Sse oe to represent the yethodDescriptor [] 2 5 - getNethodDescriptors () Bets the bean’s method descriptors propertyDescriptor [] getPropertyDescriptors() In fact, most beans don’t implement the BeanInfo interface directly. Instead, they extend the SimpleBeanInfo class, which implements BeanInfo. Here’s the inheritance diagram for simpleBeanInfo: Java. lang. Object gee |__java. beans. Simp!eBean|nfo neuter e with Java © @ SimpleBeaninfo class Table 28.4: Methods of th eT is implemented to indicate that there are no oy, BeanInfo[) es getadditionalBeanInfo () relevant BeanInfo objects | BeanDescriptor Tris implemented to indicate that there is no descripto, ~~ getBeanDescriptor () | It is implemented to deny knowledge of a default event >| dnt getDefaultEvent Index () Tris implemented to deny knowledge of a default propery | | plemented to deny knowledge of event sets | int getDefaultPropertyIndex () It is im EventSetDescriptor [] getEventSetDescriptors 0 TLis implemented to deny there are no icons available | Image getIcon (int iconKind) MethodDescriptor [] It is implemented to deny knowledge of methods getMethodDescriptors() PropertyDescriptor [] getPropertyDescriptors () Image loadimage (String resourceName) It is implemented to deny knowledge of properties The utility method used to help in loading icon images To actually describe a property, you use the PropertyDescri ich i i A ptor class, which in turn is derived fr the FeatureDescriptor class. Here’s the inheritance diagram for the FeatureDescriptor class: 3 java.lang.Object |___java. beans. FeatureDescr iptor You'll find the the Featuz iptor i Mew constructor of the FeatureDescriptor class in Table 28.5 and its methods in Tabl Table 28.5: The constructor of the FeatureDescriptor class String SECShOEt Description, ) Object getVaiue (String attrtiicenane) Wretrieves a named attribute with this feature boolean isExpert( boolean isHidden() boolean isPreferrea() void setDisplayname (string displayname) void setExpert (boolean expert) void setHidden (boolean hidden) It sets the hidden flag for features intended only for tool use Ttsets the name of this feature Tt sets the preferred flag, used to ider features that are Particularly important for presenting to people ‘You can associate a short descriptive string with a feature void setName (String name) setPreferred (boolean preferred) void setShortDescription (String text) You can associate a named attribute with this feature void setValue (String attributeName, Object value) Here's the inheritance diagram for the PropertyDescriptor class: java beans. FeatureDescr iptor eres You'll find the constructors ofthe Ps 8.8, i Descriptor class \ Table 28.7: Constructors of the Property ‘econstructs a property descriptor PropertyDescriptor (String propertyName, Class beanClass) PropertyDescriptor (String It takes the name of a simple property as well as methog propertyName, Class names for reading and writing the property beanClass, String getterName, String settexName) Te takes the name of a simple property as well as Methog objects for reading and writing the property PropertyDescriptor (String propertyName, Method getter, Method setter) Table 28.8: Methods of the PropertyDescriptor class PropertyEditor Tt creates an instance of a property editor using the current createPropertyBditor (Obje i ct bean) pope a boolean equals (Object obj) Class : I : getPropertyEditorClass(() Ea or tis it PropertyEditor class that has been Class = = = It gets the Class object for the property Method getReadMethod () It gets gets the method that should be used to read the property Method getWriteMethod () EE ; It gets the method that should be used to write the } It updates to bound i ; ~ properties and that will cause 4 " BropertyChange event to be fired when the property is bound properties and that will cause ‘ to be fired when the property i ee mediate SoWtlons Table 28.8: Methods of the = Descriptor class a 4 that will Itattempts updates t i ties an to constrained proper 2 provera, Vetoablechange event to be fired when th Property is changed Normally, property editors will be found using the Property editor manager void setConstraineg (boolean constrainea) void setPropertYEditorciags (cy ass propertyEditorciass) void setReadMethoq property, (Method getter) xt eee the method that should be used to read the prope id setWritemeth : ined setter) a It sets the method that should be used to write the Property value Let's look at an example that implements « z 5 nase, i In >, we'll ai P re te eg ena aban awe FY eee ee ae Sure the bean will be filled in with color. We'll call this new bean Bean2. sean eark Of the new £11104 property, we'll add/a private boolean variable of that name to the import java.awt.*: import java.awt.event.+; ‘public class Bean2 extends Canvas { private boolean filled; We initialize this property to False when the bean is created: — eee import java.awt.*; import java.awt. 3 public class Bean2 extends Canvas { private boolean filled; iS int count; Ser Sar Public Bean2(): (is oy oe _Choplr 26: Working wit Java Beans Gr oak fee mee. methods SCCFFSPCTSY. tang wi so Bisperty. The get method yet mn sment «propery, J neo Jement_& prope the na © Pid the get method takes an hen ym eee ape set PropertyName, wi proper ‘any supports see taac ene propery ER ATS papery Heres HOV ™® iarene est | ae inet fn oe evn ee ~ Ie die et rane comes sae ea fis eee ie eae ener (new WouserdapterO { Listener (nen Noursressea(wouseevent me) { clicked’), ) public vol Fitted = fotse: Seestz0(200, 100); ? pupie void clicked ¢ ‘count repsine 0: public bontoan gertiiiedo ( return £1110d: mee Berg sett lfed(bootean Flog) ¢ this: filled = #129; repaint: ) > 'All that’s left isto put the £111¢d property to use. Ifit's True, here's the code we add to the paint method: the bean should be filled in with coor, 0 public void paint (Graphics g) ( ‘Dimension dimension = getSize(): | int height = dimension.height; int width = dimension.width; if(Fitled) ( {g.setColor (new Color(255, 0, 0)): 9.FillRect(0, 0, --width, --height): } g-setcolor(new Color(@, 0, 0)): 9-drawString("Click count = "+ count, 50, 50): d Now we have to create a new class, Be en w class, Bean2Beantnfo, which will return information about ths” property, This class will go info the same package as the bean itself, but it’s based package. sun. deno.beang, faport Jove beens.*t public class Bean2Beaninfo extends SimpleBeaninfo { . . . ae 1292 To let Java know about aos, Fe ey at ee Oe which of a property and poin, Fiptor o} SetPropertypescriptora method, which Points '© the cage Obiects. Each Propertyeecripeor object holds the MAM / ropertyDescriptor o| Be package ‘sunw.domo, beasy> impor Java.beang.2°2"2! Public Class Beansboq Inge Public Propertypu’® extends Simp et try er escriptonns Bier sre ’ Catch (Excepeion @) ¢ d return nuit; ; wih; This is the only property in pe, return it, like this: 202, $0 We add the new PropertyDescriptor object to an array and Package sunw.demo..bean2; import java. beans public Class Bean2Beaninto extends Si leBeaninfo Public rgpertydescriptort] ore tee eo { PropertyDescriptor fitted = new PropertyDescriptor("filled", Bean2.class): PrepertyDescriptor propertydeser iptor{] = (Filed): _,feturn propertydescriptor; } catch(Exception e) () return null; } 3 abe i After compiling this new class (bean2BeanInfo. java), we place bean2BeanInfo.class in the directory demo\sunw\demo\bean2, along with the classes created when we compiled Bean2 . java. We'll need a new manifest file that includes the Bean2Bean Info class. Here’s what bean2..m£t looks like: iaice /bear nzBeaninfo.class ie ae beara /aeena Dera a) Java-Bean: True ww We place this new manifest f Bean2. jar file and install it: Chapter 28: Working “— Design Patterns for Properties rs and says, “Well, well, I have come to know about Java Bean and its xr appea in Java, how wil ‘d to make me doubly me in this regar for properties in Java. You The subset of a Bean’s state by the values assigned to the pro thod a property is obtained. The mel Il you get properties can even add color eis a property. perties. A property is sign patterns? Can you enlighten 10 different design patterns queries. What are its de: “Yes Sir’, you say. “There are tws properties to Java Bean”, you reply t© his ince of that component is determined method. By a getter () are simple and sure?” |The behavior and appearai set by a setter () ff properties. These properties re are two types of indexed. Simple Properties «s that it has a single value. It can be identified by the following, ‘The characteristic of the simple property i he name of the property and T is its type: design patterns, where N is # public T getNQ; public void setN(T arg); To access its values, a read/write property has both of these methods. A read only property has only a get () method and a write-only property has only a set ( ‘method. The following are three read/write Simple properties along with their getter () and setter () methods: private double depth, height, width; public double getDepth() { return depth: } publ ic void setDepth(double db!) { depth = dbl: public double getHeight() { return height; } publ ic void setHeight (double hdb!) { height = Rébl: } public double getWidth() { return width: } public void setWidth(double wdb!) { width = wabl: } Adding a Color Property to SimpleBean To add a Color property, you have to make the following changes to SimpleBeanapp. java: Create and initialize a private instance variable. private Color color = Color.green; Write a public getter method. public Color getColor() { return color; } Write a public setter method. public void setColor(Color newclr) { color = newclr: aN opal Oe } erride the paint() method inherited from Ca public void paint (Graphics g) { pees g.setColor(color); g.fillRect(20, 5, 20, 30);

You might also like