Вы находитесь на странице: 1из 17

JavaBeans is a portable, platform-independent component model written in the Java programming language.

The JavaBeans architecture was built through a collaborative industry effort and enables developers to write reusable components in the Java programming language. With the JavaBeans API you can create reuseable, platform-independent components. Using JavaBeans-compliant application builder tools, you can combine these components into applets, applications, or composite components. JavaBean components are known as beans. Beans are dynamic in that they can be changed or customized. Through the design mode of a builder tool, you use the property sheet or bean customizer to customize the bean and then save (persist) your customized beans.

Lesson: Using the NetBeans GUI Builder


This lesson explains how to use the NetBeans IDE GUI Builder to work with beans. In preparation for working with the GUI Builder, you should be first familiar with the key NetBeans concepts which are explained in the NetBeans IDE Java Quick Start Tutorial. This lesson guides you through the process of creating a bean pattern in the NetBeans projects, introduces the user interface of the GUI Builder, and explains how to add your bean object to the palette.

Creating a New Project


In the NetBeans IDE, you always work in a project where you store sources and files. To create a new project, perform the following steps: 1. Select New Project from the File menu. You can also click the New Project button in the IDE toolbar. 2. In the Categories pane, select the General node. In the Projects pane, choose the Java Application type. Click the Next button. 3. Enter MyBean in the Project Name field and specify the project location. Do not create a Main class here, because later you will create a new Java class in this project. 4. Click the Finish button. This figure represents the expanded MyBean node in the Projects list.

Creating a New Form

After creating a new project, the next step is to create a form within which the JavaBeans components and other required GUI components, will be placed. To create a new form, perform the following sequence of actions: 1. In the Projects list, expand the MyBean node, right-click on the <default package> node and choose New|JFrame Form from the pop-up menu. 2. Enter MyForm as the Class Name. 3. Click the Finish button. The IDE creates the MyForm form and the MyForm class within the MyBean application and opens the MyForm form in the GUI Builder. This figure represents the Projects list, where the MyForm class is located.

The GUI Builder Interface


When the JFrame form is added to your application, the IDE opens the newly-created form in an Editor tab with a toolbar containing the following buttons:

Selection Mode enables you to select one or more objects in the Design Area. Connection Mode enables you to set a connection between objects by specifying an event.

Preview Design enables you to preview the form layout. Align commands enable you to align selected objects. Change Resizability enables you to set up vertical and horizontal resizing.

When the MyForm form opens in the GUI Builder's Design view, three additional windows appear, enabling you to navigate, organize, and edit GUI forms. These windows include the following:

Design Area. The primary window for creating and editing Java GUI forms. Source and Design toggle buttons enable you to switch between view a class's source code and a graphical view of the GUI components. Click on an object to select it in the Design Area. For a multiple selection, hold down the Ctrl key while clicking on objects. Inspector. Representation of a tree hierarchy of all the components in your application. The Inspector highlights the component in the tree that is currently being edited. Palette. A customizable list of available components containing groups for Swing, AWT, Borders, and Beans components. This window enables you to create, remove, and rearrange the categories displayed in the palette using the customizer. Properties Window. A display of the properties of the component currently selected in the GUI Builder, Inspector window, Projects window, or Files window.

If you click the Source button, the IDE displays the application's Java source code in the editor. Sections of code that are automatically generated by the GUI Builder are indicated by blue areas. These blue areas are protected from editing in the Source view. You can only edit code appearing in the white areas of the editor when in Source view. When you make your changes in the Design View, the IDE updates the file's sources.

Creating a Bean
To create your own bean object and add it to the palette for the bean group, execute the following procedure: 1. 2. 3. 4. 5. Select the <default package> node in the MyBean project. Choose New|Java Class from the pop-up menu. Specify the name for the new class, for example, MyBean, then press the Finish button. Open the MyBean.java file. In the editor window, select inside the class. Right-click and choose Insert Code. Then select Add Property. 6. In the Name field of the Add Property dialog box, type YourName and press OK.

7. Now you can analyze the automatically generated code. Notice that set and get methods were included:
8. public class MyBean { 9. 10. /** Creates a new instance of MyBean */ 11. public MyBean() { 12. } 13. 14. /** 15. * Holds value of property yourName. 16. */ 17. private String yourName; 18.

19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. }

/** * Getter for property yourName. * @return Value of property yourName. */ public String getYourName() { return this.yourName; } /** * Setter for property yourName. * @param yourName New value of property yourName. */ public void setYourName(String yourName) { this.yourName = yourName; }

36. Right-click the MyBean node in the MyBean project tree and choose Tools |Add to Palette from the pop-up menu. 37. Select the Beans group in the Palette tree to add your bean. Now you can switch to the Palette window by choosing Palette from the Windows menu and make sure that the MyBean component was added to the Beans group. So far you have created a bean, set the YourName property, and added this bean as a component to the palette.

Adding Components to the Form


Now you can use the Free Design of the GUI Builder and add the MyBean component and other standard Swing components to MyForm. 1. Select the MyForm node in the project tree. 2. Drag the JLabel Swing component from the Palette window to the Design Area. Doubleclick the component and change the text property to "Enter your name:". 3. Drag the JTextField component from the Palette window to the Design Area. Doubleclick the component and empty the text field. 4. Drag the JButton component from the Palette window to the Design Area. Double-click the component and enter "OK" as the text property. 5. Add another button and enter "Cancel" as its text property. 6. Align components by using the appropriate align commands. 7. Before you drag the MyBean component from the Pallete you must compile your project because the MyBean component is non-visual and cannot be operated as a visual component. When you Drag and Drop the MyBean component it will not appear in the Design Area. However, you can view it in the Inspector window by expanding the Other Components node, as shown in the following figure.

8.

To summarize, in the previous steps you created a project, developed a JFrame form, added a bean object and included it in your project as a non-visual component. Later in this trail you will learn how to change properties for the bean component and handle events by using the NetBeans GUI Builder. Previous Trail Next

Lesson: Writing a Simple Bean


In this section you will learn more about beans by performing the following actions:

Creating a simple bean Compiling the bean Generating a Java Archive (JAR) file Loading the bean into the GUI Builder of the NetBeans IDE Inspecting the bean's properties and events

Your bean will be named SimpleBean. Here are the steps to create it: 1. Write the SimpleBean code. Put it in a file named SimpleBean.java, in the directory of your choice. Here's the code:
2. import java.awt.Color; 3. import java.beans.XMLDecoder;

4. import javax.swing.JLabel; 5. import java.io.Serializable; 6. 7. public class SimpleBean extends JLabel 8. implements Serializable { 9. public SimpleBean() { 10. setText( "Hello world!" ); 11. setOpaque( true ); 12. setBackground( Color.RED ); 13. setForeground( Color.YELLOW ); 14. setVerticalAlignment( CENTER ); 15. setHorizontalAlignment( CENTER ); 16. } 17. }

extends the javax.swing.JLabel graphic component and inherits its properties, which makes the SimpleBean a visual component. SimpleBean also implements the java.io.Serializable interface. Your bean may implement either the Serializable or the Externalizable interface.
SimpleBean

18. Create a manifest, the JAR file, and the class file SimpleBean.class. Use the Apache Ant tool to create these files. Apache Ant is a Java-based build tool that enables you to generate XML-based configurations files as follows:
19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. <?xml version="1.0" encoding="ISO-8859-1"?> <project default="build"> <dirname property="basedir" file="${ant.file}"/> <property name="beanname" value="SimpleBean"/> <property name="jarfile" value="${basedir}/${beanname}.jar"/>

<target name="build" depends="compile"> <jar destfile="${jarfile}" basedir="${basedir}" includes="*.class"> 30. <manifest> 31. <section name="${beanname}.class"> 32. <attribute name="Java-Bean" value="true"/> 33. </section> 34. </manifest> 35. </jar> 36. </target> 37. 38. <target name="compile"> 39. <javac destdir="${basedir}"> 40. <src location="${basedir}"/> 41. </javac> 42. </target> 43. 44. <target name="clean"> 45. <delete file="${jarfile}"> 46. <fileset dir="${basedir}" includes="*.class"/> 47. </delete> 48. </target> 49. 50. </project>

It is recommended to save an XML script in the build.xml file, because Ant recognizes this file name automatically 51. Load the JAR file. Use the NetBeans IDE GUI Builder to load the jar file as follows: 1. Start NetBeans. 2. From the File menu select "New Project" to create a new application for your bean. You can use "Open Project" to add your bean to an existing application. 3. Create a new application using the New Project Wizard. 4. Select a newly created project in the List of Projects, expand the Source Packages node, and select the Default Package element. 5. Click the right mouse button and select New|JFrameForm from the pop-up menu. 6. Select the newly created Form node in the Project Tree. A blank form opens in the GUI Builder view of an Editor tab. 7. Open the Palette Manager for Swing/AWT components by selecting Palette Manager in the Tools menu. 8. In the Palette Manager window select the beans components in the Palette tree and press the "Add from JAR" button. 9. Specify a location for your SimpleBean JAR file and follow the Add from JAR Wizard instructions. 10. Select the Palette and Properties options from the Windows menu. 11. Expand the beans group in the Palette window. The SimpleBean object appears. Drag the SimpleBean object to the GUI Builder panel. The following figure represents the SimpleBean object loaded in the GUI Builder panel: 52. Inspect Properties and Events. The SimpleBean properties will appear in the Properties window. For example, you can change a background property by selecting another color. To preview your form, use the Preview Design button of the GUI Builder toolbar. To inspect events associated with the SimpleBean object, switch to the Events tab of the Properties window. You will learn more about bean properties and events in the lessons that follow.

Lesson: Properties
In the following sections you will learn how to implement bean properties. A bean property is a named attribute of a bean that can affect its behavior or appearance. Examples of bean properties include color, label, font, font size, and display size. The JavaBeans specification defines the following types of bean properties: Simple A bean property with a single value whose changes are independent of changes in any other property. Indexed A bean property that supports a range of values instead of a single value.

Bound A bean property for which a change to the property results in a notification being sent to some other bean. Constrained A bean property for which a change to the property results in validation by another bean. The other bean may reject the change if it is not appropriate.

Bean properties can also be classified as follows:


Writable A bean property that can be changed o Standard 2) Expert 3)Preferred Read Only A bean property that cannot be changed. Hidden A bean property that can be changed. However, these properties are not disclosed with the BeanInfo class

BeanBuilder uses this schema to group and represent properties in the Properties window.

Lesson: Manipulating Events


Event passing is the means by which components communicate with each other. Components broadcast events, and the underlying framework delivers the events to the components that are to be notified. The notified components usually perform some action based on the event that took place. The event model was designed to accommodate the JavaBeans architecture. To understand how events and event handling work in the JavaBeans component model, you must understand the concepts of events, listeners, and sources. To refresh your knowledge in these areas, read the Writing Event Listeners lesson of the Swing tutorial. The event model that is used by the JavaBeans architecture is a delegation model. This model is composed of three main parts: sources, events, and listeners. The source of an event is the object that originates or fires the event. The source must define the events it will fire, as well as the methods for registering listeners of those events. A listener is an object that indicates that it is to be notified of events of a particular type. Listeners register for events using the methods defined by the sources of those events. From the Properties lesson you discovered two event listeners. The PropertyChangeListener(in the API reference documentation) interface provides a notification whenever a bound property value is changed and the VetoableChangeListener(in the API reference documentation) creates a notification whenever a bean changes a constrained property value.

Simple Event Example


This example represents an application that performs an action when a button is clicked. Button components are defined as sources of an event type called ActionEvent(in the API reference documentation). Listeners of events of this type must register for these events using the addActionListener method. Therefore, the addActionListener method is used to register the ButtonHandler object as a listener of the ActionEvent event that is fired by the button. In addition, according to the requirements of the ActionListener class, you must define an actionPerformed method, which is the method that is called when the button is clicked.
import import import import import import import java.awt.event.ActionEvent; java.awt.event.ActionListener; javax.swing.JTextArea; java.awt.BorderLayout; javax.swing.JButton; javax.swing.JFrame; javax.swing.WindowConstants;

public class ButtonHandler implements ActionListener { /** * Component that will contain messages about

* events generated. */ private JTextArea output; /** * Creates an ActionListener that will put messages in * JTextArea everytime event received. */ public ButtonHandler( JTextArea output ) { this.output = output; } /** * When receives action event notification, appends * message to the JTextArea passed into the constructor. */ public void actionPerformed( ActionEvent event ) { this.output.append( "Action occurred: " + event + '\n' ); } } class ActionTester { public static void main(String args[]) { JFrame frame = new JFrame( "Button Handler" ); JTextArea area = new JTextArea( 6, 80 ); JButton button = new JButton( "Fire Event" ); button.addActionListener( new ButtonHandler( area ) ); frame.add( button, BorderLayout.NORTH ); frame.add( area, BorderLayout.CENTER ); frame.pack(); frame.setDefaultCloseOperation( WindowConstants.DISPOSE_ON_CLOSE ); frame.setLocationRelativeTo( null ); frame.setVisible( true ); } }

Using Introspection to Discover the Events A Bean Fires


The JavaBeans API provides event-oriented design patterns to give introspecting tools the ability to discover what events a bean can fire. For a bean to be the source of an event, it must implement methods that add and remove listener objects for that type of event. The design patterns for these methods are the following:
public void add<EventListenerType>(<EventListenerType> a) public void remove<EventListenerType>(<EventListenerType> a)

These methods let a source bean know where to fire events. The source bean then fires events at those listener beans using the methods for those particular interfaces. For example, if a source bean registers ActionListener objects, it will fire events at those objects by calling the actionPerformed method on those listeners.
package java.awt.event; import java.util.EventListener; public interface ActionListener extends EventListener { public void actionPerformed(ActionEvent e); }

Using the NetBeans GUI Builder to Set Events


In the lesson "Using the NetBeans GUI Builder," you learned how to create a MyBean component, add the yourName property, and design a simple form. Now you will set an event by which a value entered in the JTextField component is stored in the yourName property. Use the GUI Builder as follows to set such an event: 1. Left click the MyForm node. 2. Switch to the Connection Mode by clicking the appropriate button on the GUI Builder toolbar. 3. In the Design Area or Inspector window select the OK button (jButton1). Notice that the button is highlighted in red when it is selected. 4. In the Inspector window select the myBean1 component. 5. In the Connection wizard's Select Source Event page, select the action| actionPerformed[jButton1ActionPerformed1] event by expanding the event type directory nodes, as represented in the following figure.

6. Click the Next button. 7. In the Specify Target Operation page, specify the yourName property in the MyBean component, and click the Next button. 8. In the Enter Parameters page, specify the target property by selecting the Property radio button. 9. Press the ellipsis (...) button to display the Select Property dialog box.

10. In the Select Property dialog box select the jTextField component from the Component combobox and choose the text property from the list that is presented, as shown on the following figure.

11. Click the Finish button. The Source Editor window is now displayed. Since the GUI Builder automatically generates the code to connect the form's components, the following code will be added to the MyForm class:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { myBean1.setYourName(jTextField1.getText()); }

Basic Bean Concepts


Individual Java Beans will vary in functionality, but most share certain common defining features.

Support for introspection allowing a builder tool to analyze how a bean works. Support for customization allowing a user to alter the appearance and behavior of a bean. Support for events allowing beans to fire events, and informing builder tools about both the events they can fire and the events they can handle. Support for properties allowing beans to be manipulated programatically, as well as to support the customization mentioned above. Support for persistence allowing beans that have been customized in an application builder to have their state saved and restored. Typically persistence is used with an application builder's save and load menu commands to restore any work that has gone into constructing an application.

While Beans are intended to be used primarily with builder tools, they need not be. Beans can be manually manipulated by text tools through programatic interfaces. All key APIs, including support for events, properties, and persistence, have been designed to be easily read and understood by human programmers as well as by builder tools.

JavaBeans Overview
The JavaBeans white paper defines a Bean as follows: A Java Bean is a reusable software component that can be manipulated visually in a builder tool. Well, if you have to sum it up in one sentence, this is as good as any. But it's pretty difficult to sum up an entire component architecture in one sentence. Beans will range greatly in their features and capabilities. Some will be very simple and others complex; some will have a visual aspect and others won't. Therefore, it isn't easy to put all Beans into a single category. Let's take a look at some of the most important features and issues surrounding Beans. This should set the stage for the rest of the book, where we will examine the JavaBeans technology in depth.

Properties, Methods, and Events


Properties are attributes of a Bean that are referenced by name. These properties are usually read and written by calling methods on the Bean specifically created for that purpose. A property of the thermostat component mentioned earlier in the chapter could be the comfort temperature. A programmer would set or get the value of this property through method calls, while an application developer using a visual development tool would manipulate the value of this property using a visual property editor. The methods of a Bean are just the Java methods exposed by the class that implements the Bean. These methods represent the interface used to access and manipulate the component. Usually, the set of public methods defined by the class will map directly to the supported methods for the Bean, although the Bean developer can choose to expose only a subset of the public methods. Events are the mechanism used by one component to send notifications to another. One component can register its interest in the events generated by another. Whenever the event occurs, the interested component will be notified by having one of its methods invoked. The process of registering interest in an event is carried out simply by calling the appropriate method on the component that is the source of the event. In turn, when an event occurs a method will be invoked on the component that registered its interest. In most cases, more than one component can register for event notifications from a single source. The component that is interested in event notifications is said to be listening for the event.

Introspection
Introspection is the process of exposing the properties, methods, and events that a JavaBean component supports. This process is used at run-time, as well as by a visual development tool at design-time. The default behavior of this process allows for the automatic introspection of any Bean. A low-level reflection mechanism is used to analyze the Bean's class to determine its methods. Next it applies some simple design patterns to determine the properties and events that are supported. To take advantage of reflection, you only need to follow a coding style that matches the design pattern. This is an important feature of JavaBeans. It means that you don't have to do anything more than code your methods using a simple convention. If you do, your Beans will automatically support introspection without you having to write any extra code. Design patterns are explained in more detail later in the chapter.

This technique may not be sufficient or suitable for every Bean. Instead, you can choose to implement a BeanInfo class which provides descriptive information about its associated Bean explicitly. This is obviously more work than using the default behavior, but it might be necessary to describe a complex Bean properly. It is important to note that the BeanInfo class is separate from the Bean that it is describing. This is done so that it is not necessary to carry the baggage of the BeanInfo within the Bean itself. If you're writing a development tool, an Introspector class is provided as part of the Beans class library. You don't have to write the code to accomplish the analysis, and every tool vendor uses the same technique to analyze a Bean. This is important to us as programmers because we want to be able to choose our development tools and know that the properties, methods, and events that are exposed for a given component will always be the same.

Customization
When you are using a visual development tool to assemble components into applications, you will be presented with some sort of user interface for customizing Bean attributes. These attributes may affect the way the Bean operates or the way it looks on the screen. The application tool you use will be able to determine the properties that a Bean supports and build a property sheet dynamically. This property sheet will contain editors for each of the properties supported by the Bean, which you can use to customize the Bean to your liking. The Beans class library comes with a number of property editors for common types such as float, boolean, and String. If you are using custom classes for properties, you will have to create custom property editors to associate with them. In some cases the default property sheet that is created by the development tool will not be good enough. You may be working with a Bean that is just too complex to customize easily using the default sheet. Beans developers have the option of creating a customizer that can help the user to customize an instance of their Bean. You can even create smart wizards that guide the user through the customization process. Customizers are also kept separate from the Bean class so that it is not a burden to the Bean when it is not being customized. This idea of separation is a common theme in the JavaBeans architecture. A Bean class only has to implement the functionality it was designed for; all other supporting features are implemented separately.

Persistence
It is necessary that Beans support a large variety of storage mechanisms. This way, Beans can participate in the largest number of applications. The simplest way to support persistence is to take advantage of Java Object Serialization. This is an automatic mechanism for saving and restoring the state of an object. Java Object Serialization is the best way to make sure that your Beans are fully portable, because you take advantage of a standard feature supported by the core Java platform. This, however, is not always desirable. There may be cases where you want your Bean to use other file formats or mechanisms to save and restore state. In the future, JavaBeans will support an alternative externalization mechanism that will allow the Bean to have complete control of its persistence mechanism.

Design-Time vs. Run-Time


JavaBeans components must be able to operate properly in a running application as well as inside an application development environment. At design-time the component must provide the design information necessary to edit its properties and customize its behavior. It also has to expose its methods and events so that the design tool can write code that interacts with the Bean at run-time. And, of course, the Bean must support the run-time environment.

Visibility
There is no requirement that a Bean be visible at run-time. It is perfectly reasonable for a Bean to perform some function that does not require it to present an interface to the user; the Bean may be controlling access to a specific device or data feed. However, it is still necessary for this type of component to support the visual application builder. The component can have properties, methods, and events, have persistent state, and interact with other Beans in a larger application. An "invisible" run-time Bean may be shown visually in the application development tool, and may provide custom property editors and customizers.

Multithreading
The issue of multithreading is no different in JavaBeans than it is in conventional Java programming. The JavaBeans architecture doesn't introduce any new language constructs or classes to deal with threading. You have to assume that your code will be used in a multithreaded application. It is your responsibility to make sure your Beans are thread-safe. Java makes this easier than in most languages, but it still requires some careful planning to get it right. Remember, thread-safe means that your Bean has anticipated its use by more than one thread at a time and has handled the situation properly.

Security
Beans are subjected to the same security model as standard Java programs. You should assume that your Bean is running in an untrusted applet. You shouldn't make any design decisions that require your Bean to be run in a trusted environment. Your Bean may be downloaded from the World Wide Web into your browser as part of someone else's applet. All of the security restrictions apply to Beans, such as denying access to the local file system, and limiting socket connections to the host system from which the applet was downloaded. If your Bean is intended to run only in a Java application on a single computer, the Java security constraints do not apply. In this case you might allow your Bean to behave differently. Be careful, because the assumptions you make about security could render your Bean useless in a networked environment.

Using Design Patterns


The JavaBeans architecture makes use of patterns that represent standard conventions for names, and type signatures for collections of methods and interfaces. Using coding standards is always a good idea because it makes your code easier to understand, and therefore easier to maintain. It also makes it easier for another programmer to understand the purpose of the methods and interfaces used by your component. In the JavaBeans architecture, these patterns have even more

significance. A set of simple patterns are used by the default introspection mechanism to analyze your Bean and determine the properties, methods, and events that are supported. These patterns allow the visual development tools to analyze your Bean and use it in the application being created. The following code fragment shows one such pattern:
public void setTemperatureColor(Color newColor) { . . . } public Color getTemperatureColor() { . . . }

These two methods together use a pattern that signifies that the Bean contains a property named TemperatureColor of type Color. No extra development is required to expose the property. The various patterns that apply to Beans development will be pointed out and discussed throughout this book. I'll identify each pattern where the associated topic is being discussed. NOTE: The use of the term "design pattern" here may be confusing to some readers. This term is commonly used to describe the practice of documenting a reusable design in object-oriented software. This is not entirely different than the application of patterns here. In this case, the design of the component adheres to a particular convention, and this convention is reused to solve a particular problem. As mentioned earlier, this convention is not a requirement. You can implement a specific BeanInfo class that fully describes the properties, methods, and events supported by your Bean. In this case, you can name your methods anything you please.

Вам также может понравиться