Java Beans
JavaBean
https://www.javatpoint.com/java-bean
• A JavaBean is a Java class that should follow the following
conventions:
– It should have a no-arg constructor.
– It should be Serializable.
– It should provide methods to set and get the values of the
properties, known as getter and setter methods.
Why use JavaBean?
• According to Java white paper, it is a reusable software
component.
• A bean encapsulates many objects into one object so that
we can access this object from multiple places.
• Moreover, it provides easy maintenance.
JavaBean Properties
• A JavaBean property is a named feature that can be
accessed by the user of the object.
• The feature can be of any Java data type, containing the
classes that you define.
• A JavaBean property may be read, write, read-only, or write-
only.
• JavaBean features are accessed through two methods in the JavaBean's
implementation class:
• 1. getPropertyName ()
• For example, if the property name is firstName, the method name would
be to read that property. This method is called the accessor.
• 2. setPropertyName ()
• For example, if the property name is firstName, the method name would
be setFirstName() to write that property. This method is called the
mutator.
• Advantages of JavaBean
– The following are the advantages of JavaBean:/p>
– The JavaBean properties and methods can be exposed to another
application.
– It provides an easiness to reuse the software components.
• Disadvantages of JavaBean
– The following are the disadvantages of JavaBean:
– JavaBeans are mutable. So, it can't take advantages of immutable
objects.
– Creating the setter and getter method for each property separately
may lead to the boilerplate code.
(In computer programming, boilerplate code or boilerplate refers to
sections of code that have to be included in many places with little or
no alteration. It is often used when referring to languages that are
considered verbose, i.e. the programmer must write a lot of code to do
minimal jobs.)[https://www.freecodecamp.org/news/whats-boilerplate-
and-why-do-we-use-it-let-s-check-out-the-coding-style-guide-
ac2b6c814ee7/]
Advantages of JavaBean- Notes
1)The java beans posses the property of “Write once and run anywhere”.
2)Beans can work in different local platforms.
3)Beans have the capability of capturing the events sent by other objects
and vice versa enabling object communication.
4)The properties, events and methods of the bean can be controlled by the
application developer.(ex. Add new properties)
5) Beans can be configured with the help of auxiliary (secondary or
supporting) software during design time.(no hassle at runtime)
6) The configuration setting can be made persistent.(reused)
7) Configuration setting of a bean can be saved in persistent storage and
restored later.
Notes
• JAR file:
• _ JAR file allows you to efficiently deploy a set of classes
and their associated resources.
• _ JAR file makes it much easier to deliver, install, and
download. It is compressed.
• Java Archive File
• • The files of a JavaBean application are compressed and
grouped as JAR files to reduce
• the size and the download time of the files.
• Generate a JAR file
• _ Syntax for creating jar file using manifest file
• C:\Beans >jar cfm MyBean.jar MyBean.mf MyBean.class
• The syntax to create a JAR file from the command prompt is:
• • jar <options><file_names>
• • The file_names is a list of files for a JavaBean application that are
stored in the JAR file.
• The various options that you can specify while creating a JAR file are:
c: Indicates the new JAR file is created.
f: Indicates that the first file in the file_names list is the name of the JAR
file.
m: Indicates that the second file in the file_names list is the name of the
manifest file.
t: Indicates that all the files and resources in the JAR file are to be
displayed in a tabular format.
v: Indicates that the JAR file should generate a verbose output.
x: Indicates that the files and resources of a JAR file are to be extracted.
o: Indicates that the JAR file should not be compressed.
M: Indicates that the manifest file is not created.
Java program of JavaBean class?
package abc;
public class Student implements java.io.Serializable
{
private int id;
private String name;
public Student()
{
}
public void setId(int id)
{
this.id = id;
}
public int getId()
{
return id;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
// Java program to access JavaBean class
package abc;
public class Test {
public static void main(String args[])
{
Student s = new Student(); // object is created
s.setName("Advanced java programming"); // setting value to the object
System.out.println(s.getName());
}
}
Application Builder Tools
(Complete Reference – 5th edition )
• When working with Java Beans, most developers use an application
builder tool, a utility that enables you to configure a set of Beans, connect
them together, and produce a working application.
• In general, Bean builder tools have the following capabilities.
■ A palette is provided that lists all of the available Beans. As additional
Beans are developed or purchased, they can be added to the palette.
■ A worksheet is displayed that allows the designer to lay out Beans in a
graphical user interface. A designer may drag and drop a Bean from the
palette to this worksheet.
■ Special editors and customizers allow a Bean to be configured. This
is the mechanism by which the behavior of a Bean may be adapted for a
particular environment
• Commands allow a designer to inquire about the state and behavior of
a Bean. This information automatically becomes available when a Bean is
added to the palette.
• Capabilities exist to interconnect Beans. This means that events
generated by one component are mapped to method invocations on
other components.
• When a collection of Beans has been configured and connected, it is
possible to save all of this information in a persistent storage area. At a
later time, this information can then be used to restore the state of the
application.
• Sun provides two Bean application builder tools.
• The first is the BeanBox, which is part of the Bean Developers Kit
(BDK). The BDK is the original builder tool provided by Sun.
• The second is the new Bean Builder. Because Bean Builder is designed to
supplant the BeanBox, Sun has stopped development of the BDK and all
new Bean applications will be created using Bean Builder
Using the Bean Developer Kit (BDK)
• The Bean Developer Kit (BDK), available from the JavaSoft site, is a simple
example of a tool that enables you to create, configure, and connect a set of
Beans.
• The BDK is for use with versions of Java 2 prior to 1.4.
• Installing the BDK
• The BDK can then be downloaded from the JavaSoft site
(http://java.sun.com).
• It is packaged as one file that is a self-extracting archive.
Starting the BDK
• To start the BDK, follow these steps:
• 1. Change to the directory c:\bdk\beanbox.
• 2. Execute the batch file called run.bat.
– This causes the BDK to display the three windows shown in Figure 25-
1.
– ToolBox lists all of the different Beans that have been included with
the BDK.
– BeanBox provides an area to lay out and connect the Beans selected
from the ToolBox.
– Properties provides the ability to configure a selected Bean.
– You may also see a window called Method Tracer, but we won’t be
using it.
Using the BDK
• This section describes how to create an application by using some of the
Beans provided with the BDK.
• First, the Molecule Bean displays a three-dimensional view of a
molecule.
• It may be configured to present one of the following molecules:
hyaluronic acid, benzene, buckminsterfullerine, cyclohexane, ethane,
or water.
• This component also has methods that allow the molecule to be rotated
in space along its X or Y axis.
• Second, the OurButton Bean provides a push-button functionality.
• We will have one button labeled “Rotate X” to rotate the molecule along
its X axis and another button labeled “Rotate Y” to rotate the molecule
along its Y axis.
• Figure 25-2 shows how this application appears.
Create and Configure an Instance of the Molecule Bean
• Follow these steps to create and configure an instance of the Molecule
Bean:
1. Position the cursor on the ToolBox entry labeled Molecule and click
the left mouse button. You should see the cursor change to a cross.
2. Move the cursor to the BeanBox display area and click the left mouse
button in approximately the area where you wish the Bean to be
displayed. You should see a rectangular region appear that contains a
3-D display of a molecule. This area is surrounded by a hatched border,
indicating that it is currently selected.
3. You can reposition the Molecule Bean by positioning the cursor over
one of the hatched borders and dragging the Bean.
• 4. You can change the molecule that is displayed by changing the
selection in the Properties window. Notice that the Bean display changes
immediately when you change the selected molecule.
Create and Configure an Instance of the OurButton Bean
• Follow these steps to create and configure an instance of the OurButton
Bean and connect it to the Molecule Bean:
• 1. Position the cursor on the ToolBox entry labeled OurButton and click
the left mouse button. You should see the cursor change to a cross.
• 2. Move the auxiliary software button in approximately the area where
you wish the Bean to be displayed. You auxiliary software appear that
contains a button. This area is surrounded by a hatched border
indicating that it is currently selected.
• 3. You may reposition the OurButton Bean by positioning the cursor
over one of the hatched borders and dragging the Bean
4. Go to the Properties window and change the label of the Bean to “Rotate
X”. The button appearance changes immediately when this property is
changed.
5. Go to the menu bar of the BeanBox and select Edit | Events | action |
actionPerformed. You should now see a line extending from the button to
the cursor. Notice that one end of the line moves as the cursor moves.
However, the other end of the line remains fixed at the button.
6. Move the cursor so that it is inside the Molecule Bean display area, and
click the left mouse button. You should see the Event Target Dialog dialog
box.
7. The dialog box allows you to choose a method that should be invoked when
this button is clicked. Select the entry labeled “rotateOnX” and click the
OK button. You should see a message box appear very briefly, stating that
the tool is “Generating and compiling adaptor class.”
• Test the application.
• Each time you press the button, the molecule should move a few degrees
around one of its axes.
• Now create another instance of the OurButton Bean. Label it “Rotate Y”
and map its action event to the “rotateY” method of the Molecule Bean.
• The steps to do this are very similar to those just described for the
button labeled “Rotate X”.
• Test the application by clicking these buttons and observing how the
molecule moves.
JAR Files
• Before developing your own Bean, it is necessary for you to understand
JAR (Java Archive) files, because tools such as the BDK expect Beans to
be packaged within JAR files.
• A JAR file allows you to efficiently deploy a set of classes and their
associated resources.
• For example, a developer may build a multimedia application that uses
various sound and image files.
• A set of Beans can control how and when this information is presented.
• All of these pieces can be placed into one JAR file.
• JAR technology makes it much easier to deliver and install software.
• Also, the elements in a JAR file are compressed, which makes
downloading a JAR file much faster than separately downloading
several uncompressed files.
• Digital signatures may also be associated with the individual elements
in a JAR file.
• This allows a consumer to be sure that these elements were produced by
a specific organization or individual.
• Note:- The package java.util.zip contains classes that read and write JAR
files.
Manifest Files
• A developer must provide a manifest file to indicate which of the components
in a JAR file are Java Beans.
• An example of a manifest file is provided in the following listing.
• It defines a JAR file that contains four .gif files and one .class file.
• The last entry is a Bean.
Name: sunw/demo/slides/slide0.gif
Name: sunw/demo/slides/slide1.gif
Name: sunw/demo/slides/slide2.gif
Name: sunw/demo/slides/slide3.gif
Name: sunw/demo/slides/Slides.class
Java-Bean: True
• A manifest file may reference several .class files.
•
• If a .class file is a Java Bean, its entry must be immediately followed by the
line “Java-Bean: True”.
The JAR Utility
• A utility is used to generate a JAR file.
• Its syntax is shown here:
jar options files
• Table 25-1 lists the possible options and their meanings.
• The following examples show how to use this utility
• Creating a JAR File
• The following command creates a JAR file named Xyz.jar that contains
all of the .class and .gif files in the current directory:
– jar cf Xyz.jar *.class *.gif
• If a manifest file such as Yxz.mf is available, it can be used with the
following command:
– jar cfm Xyz.jar Yxz.mf *.class *.gif
• Tabulating the Contents of a JAR File
• The following command lists the contents of Xyz.jar:
jar tf Xyz.jar
• Extracting Files from a JAR File
• The following command extracts the contents of Xyz.jar and places those
files in the current directory:
jar xf Xyz.jar
• Updating an Existing JAR File
• The following command adds the file file1.class to Xyz.jar:
jar -uf Xyz.jar file1.class
• Recursing Directories
• The following command adds all files below directoryX to Xyz.jar:
jar -uf Xyz.jar -C directoryX *
Developing a Simple Bean Using the BDK
• Pg no – 897 to 902 from Java Complete Reference 5th edition
Using Bound Properties
• A Bean that has a bound property generates an event when the
property is changed.
• The event is of type PropertyChangeEvent and is sent to objects that
previously registered an interest in receiving such notifications.
• The TickTock Bean is supplied with the BDK. It generates a property
change event every N seconds.
• N is a property of the Bean that can be changed via the Properties
window of the BDK.
• The next example builds an application that uses the TickTock Bean to
automatically control the Colors Bean.
• Figure 25-4 shows how this application appears
Steps
• For this example, start the BDK and create an instance of the Colors
Bean in the BeanBox window.
• Create an instance of the TickTock Bean. The Properties window should
show one property for this component.
• It is “Interval” and its initial value is 5.
• This represents the number of seconds that elapse between property
change events generated by the TickTock Bean.
• Change the value to 1.
• Now you need to map events generated by the TickTock Bean into method
calls on the Colors Bean.
• Follow these steps:
• 1. Go to the menu bar of the BeanBox and select Edit | Events |
propertyChange | propertyChange. You should now see a line extending from
the button to the cursor.
• 2. Move the cursor so that it is inside the Colors Bean display area, and
click the left mouse button. You should see the Event Target Dialog dialog
box.
• 3. The dialog box allows you to choose a method that should be invoked
when this event occurs. Select the entry labeled “change” and click the OK
button. You should see a message box appear very briefly, stating that the
tool is “Generating and compiling adaptor class.”
• You should now see the color of your component change every second.
Constrained Properties
• A Bean that has a constrained property generates an event when an
attempt is made to change its value.
• The event is of type PropertyChangeEvent.
• It is sent to objects that previously registered an interest in receiving
such notifications.
• Those other objects have the ability to veto the proposed change.
• This capability allows a Bean to operate differently according to its
run-time environment.
Persistence
• Persistence is the ability to save a Bean to nonvolatile storage and
retrieve it at a later time.
• The information that is particularly important are the configuration
settings.
• Let us first see how the BDK allows you to save a set of Beans that have
been configured and connected together to form an application.
• Recall our previous example involving both the Colors and TickTock
Beans.
• The rectangular property of the Colors Bean was changed to true, and
the interval property of the TickTock Bean was changed to one second.
• These changes can be saved.
• To save the application, go to the menu bar of the BeanBox and select
File | Save.
• A dialog box should appear, allowing you to specify the name of a file to
which the Beans and their configuration parameters should be saved.
• Supply a filename and click the OK button on that dialog box. Exit from
the BDK.
• Start the BDK again.
• To restore the application, go to the menu bar of the BeanBox and select
File | Load.
• A dialog box should appear, allowing you to specify the name of the file
from which an application should be restored.
• Supply the name of the file in which the application was saved, and
click the OK button.
• Your application should now be functioning.
• Confirm that the rectangular property of the Colors Bean is true and that
the interval property for the TickTock Bean is equal to one second.
• The object serialization capabilities provided by the Java class libraries
are used to provide persistence for Beans.
• If a Bean inherits directly or indirectly from java.awt.Component, it is
automatically serializable, because that class implements the
java.io.Serializable interface.
• If a Bean does not inherit an implementation of the Serializable
interface, you must provide this yourself.
• Otherwise, containers cannot save the configuration of your component.
• The transient keyword can be used to designate data members of a Bean
that should not be serialized.
• The color variable of the Colors class is an example of such an item.
Customizers
• The Properties window of the BDK allows a developer to modify the
properties of a Bean.
• However, this may not be the best user interface for a complex
component with many interrelated properties.
• Therefore, a Bean developer can provide a customizer that helps another
developer configure this software.
• 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.
• A Bean developer has great flexibility to develop a customizer that can
differentiate his or her product in the marketplace
The Java Beans API
• The Java Beans functionality is provided by a set of classes and
interfaces in the java.beans package.
• This section provides a brief overview of its contents.
• Table 25-2 lists the interfaces in java.beans and provides a brief
description of their functionality.
• Table 25-3 lists the classes in java.beans.
• And many more classes are defined
For information and many more in the book of complete
reference
Introspection
• Introspection is the process of analyzing a Bean to determine its
capabilities.
• This is an essential feature of the Java Beans API, because it allows an
application builder tool to present information about a component to a
software designer.
• Without introspection, the Java Beans technology could not operate.
• There are two ways in which the developer of a Bean can indicate which
of its properties, events, and methods should be exposed by an
application builder tool.
• With the first method, simple naming conventions are used.
• These allow the introspection mechanisms to infer information about a
Bean.
• In the second way, an additional class is provided that explicitly
supplies this information
• The following sections indicate the design patterns for properties and
events that enable the functionality of a Bean to be determined.
Design Patterns for Properties
• A property is a subset of a Bean’s state.
• The values assigned to the properties determine the behavior and
appearance of that component.
• This section discusses three types of properties:
– simple, Boolean, and indexed.
Simple Properties
• A simple property has a single value.
• It can be identified by the following design patterns, where N is the
name of the property and T is its type.
public T getN( );
public void setN(T arg);
• A read/write property has both of these methods to access its values.
• A read-only property has only a get method.
• A write-only property has only a set method.
• The following listing shows a class that has three read/write simple properties:
public class Box {
private double depth, height, width;
public double getDepth( ) {
return depth;
}
public void setDepth(double d) {
depth = d;
}
public double getHeight( ) {
return height;
}
public void setHeight(double h) {
height = h;
}
public double getWidth( ) {
return width;
}
public void setWidth(double w) {
width = w;
}
}
Boolean Properties
• A Boolean property has a value of true or false.
• It can be identified by the following design patterns, where N is the name of the
property:
– public boolean isN( );
– public boolean getN( );
– public void setN(boolean value);
• Either the first or second pattern can be used to retrieve the value of a Boolean
property.
• However, if a class has both of these methods, the first pattern is used.
The following listing shows a class that has one Boolean property:
public class Line
{
private boolean dotted = false;
public boolean isDotted( )
{
return dotted;
}
public void setDotted(boolean dotted)
{
this.dotted = dotted;
}
}
Indexed Properties
• An indexed property consists of multiple values.
• It can be identified by the following design patterns, where N is the
name of the property and T is its type:
– public T getN(int index);
– public void setN(int index, T value);
– public T[ ] getN( );
– public void setN(T values[ ]);
• The following listing shows a class that has one read/write indexed property:
public class PieChart
{
private double data[ ];
public double getData(int index)
{
return data[index];
}
public void setData(int index, double value)
{
data[index] = value;
}
public double[ ] getData( )
{
return data;
}
public void setData(double[ ] values)
{
data = new double[values.length];
System.arraycopy(values, 0, data, 0, values.length);
}
}
Design Patterns for Events
• Beans use the delegation event model.
• Beans can generate events and send them to other objects.
• These can be identified by the following design patterns, where T is the
type of the event:
– public void addTListener(TListener eventListener);
– public void addTListener(TListener eventListener) throws
TooManyListeners;
– public void removeTListener(TListener eventListener);
• These methods are used by event listeners to register an interest in
events of a specific type.
• The first pattern indicates that a Bean can multicast an event to multiple
listeners.
• The second pattern indicates that a Bean can unicast an event to only
one listener.
• The third pattern is used by a listener when it no longer wishes to receive
a specific type of event notification from a Bean.
• The following listing outlines a class that notifies other objects when a
temperature value moves outside a specific range.
• The two methods indicated here allow other objects that implement the
TemperatureListener interface to receive notifications when this occurs.
public class Thermometer {
public void addTemperatureListener(TemperatureListener tl) {
...
}
public void removeTemperatureListener(TemperatureListener tl) {
...
}
}
Methods
• Design patterns are not used for naming nonproperty methods.
• The introspection mechanism finds all of the public methods of a Bean.
• Protected and private methods are not presented.
• https://www.javatpoint.com/how-to-make-an-executable-jar-
file-in-java
• https://docs.oracle.com/javase/tutorial/deployment/jar/basicsin
dex.html
• https://javarevisited.blogspot.com/2012/03/how-to-create-and-
execute-jar-file-in.html
• https://code.google.com/archive/p/jbaindi/downloads?page=3
Developing a Simple Bean Using the BDK
• Page no 897 to 901