NetBeansJavaBeansTutorial

The NetBeans JavaBeans Tutorial

Wade Chandler

Work in progress. Currently I'm turning this into a set of articles. Once those have been completed for a while I'll transfer the final information here.

Are these things for making coffee or making software? I thought I smelled them in StarBucks, then I realized I was smelling my cafe mocha! In this tutorial, you'll learn how to create and work with JavaBeans and their features inside NetBeans, but this tutorial will work for anyone intersted in JavaBeans and learning more about them.


Introduction

Many people ask on the mailing lists and forums how to create JavaBeans, get custom property editors or JavaBean customizers working, or how all these things with JavaBeans work. Once they get over the initial hump, they then wonder what is the deal with paintValue, getAsText, and getJavaInitializationString. This tutorial will address all things JavaBeans from the view of using them inside NetBeans or a generic JavaBean container.

Contents


What is a JavaBean, and who drank my coffee?

Found my coffee. Never mind.

OK, a JavaBean is really nothing more than a Java class with some special patterns or helper classes. This and the other sections explain this in detail. The basics are in this section.

Most JavaBean APIs, including the standard package java.beans, require a class to have a default or a no argument constructor, so always include one; you're life will be easier for it. Beyond that, a JavaBean/class needs properties to be useful as this is where accessible data or state is kept, and most JavaBean containers require the use of something called property change events to update the screen or other resources correctly as properties of the JavaBean are modified (this is true for the Java binding framework as well).

As this tutorial is written around using JavaBeans in some generic JavaBean container, I'll be following the JavaBeans 1.01 specification which added property change events. NetBeans follows this convention. More information on the entire specification may be located at: http://java.sun.com/javase/technologies/desktop/javabeans/api/index.html

and some other useful info at: http://java.sun.com/javase/technologies/desktop/javabeans/docs/index.html

What is a property?

I mentioned properties contain JavaBean state in the previous section. Properties can be read-only or read-write. One can technically have a write-only property though the result will vary across containers whether errors will be raised or whether the property will show up at all. How can a property be shown if it can't be read?

Note: It is beneficial to keep in mind, and is why I'm going ahead and mentioning this here even though I have a section devoted to them, that most bean containers require the use of property change events within properties. I do not go further into this in this section, but I did want to make it very clear so you are sure to know this in case issues arise. See the section on property change events for more information.

In the most generic sense of the JavaBeans specifications a property is based on method name patterns. Imagine we have a property firstName. The read-only version:


    //just a variable name...could be
    ///firstname, _firstName, first_name, etc
    private String firstName = null;
   
    //method name should follow this pattern
    public String getFirstName(){
        return firstName;
    }

The above method pattern tells the JavaBeans base APIs there is a property named firstName and the fact there is no method setFirstName accepting a String as a single parameter means it is read-only. The read-write would be:

    //just a variable name...could be
    ///firstname, _firstName, first_name, etc
    private String firstName = null;
   
    //method name should follow this pattern
    public String getFirstName(){
        return firstName;
    }

    public void setFirstName(String fname){
        firstName = fname;
    }

Hint: I use scope and this and keep the parameter variable names the same as the field names. To me this is more clear:

 
    public void setFirstName(String firstName){
        this.firstName = firstName;
    }

Hint: It is sometimes useful to be able to chain method calls together to set properties one after another to keep from having to type the bean variable name over and over again. Imagine we have a class Person and we want to setFirstName, setLastName, and setPhoneNumber all without typing a Person instance variable name 3 times. We could create our write methods for these properties with this pattern:

    public Person setFirstName(String firstName){
        this.firstName = firstName;
        return this;
    }

    public Person setLastName(String lastName){
        this.lastName = lastName;
        return this;
    }

    public Person setPhoneNumber(String phoneNumber){
        this.phoneNumber = phoneNumber;
        return this;
    }

And, these methods would still work for the JavaBean property method patterns for read-write properties. The return won't affect the pattern, and then we can later write this code in standard Java:


    Person person = new Person();
    person.setFirstName("Wade")
          .setLastName("Chandler)
          .setPhoneNumber("555-5555");

Which wouldn't be such a big deal if we were using short variable names such as p, but sometimes a longer variable name is needed to make something more clear. Perhaps such a case would be when you have a manager and an employee or maybe assistantManager.

Assuming you the reader must be technical as you're reading this tutorial I'll assume you have picked up on the pattern. But, to be clear, the standard JavaBeans patterns use get[[[PropertyName | [PropertyName]] and set[[[PropertyName | [PropertyName]] for everything but boolean properties, and boolean properties use the pattern is[[[PropertyName | [PropertyName]] and set[[[PropertyName | [PropertyName]] though it is perfectly fine to use get/set for boolean properties.

The used case pattern is known as camel case. This means getPropertyName insinuates a property named propertyName and getName insinuates a property named name. Pretty simple.

The above being stated, properties method names do not actually have to use the standard patterns. However, the Java environment can not infer properties not using the patterns on its own. To use different names you'll need a property descriptor. This is detailed later.

Regardless of how a properties value is accessed, meaning regardless of the method names used to access the properties information, a property does have a name. This name is used by many APIs, tools, and scripting languages to access a beans properties versus using the Java language set and get methods.

Perhaps one of the most confusing aspects of JavaBeans is their properties can not be accessed directly by name from the Java language itself. This is useful to commit to memory, at least in the known future of the Java language. Using something like Groovy, Jython, or some of the other scripting languages can make using JavaBeans much easier as within these languages properties may be accessed directly by name versus having to use the class methods which makeup the property.

Besides single value properties. The JavaBeans standards support indexed properties. These are properties accessed by index instead of just by name. An example of a simple indexed property is:


    //it is usually a good idea to not make an index property null
    //as this can cause different issues in bean editors such as
    //NetBeans's Mattisse
    private String[] members = new String[0];
    
    public String getMembers(int ndx){
        return members[ndx];
    }

    public void setMembers(int ndx, String member){
        members[ndx] = member;
    }

    public String[] getMembers(){
        return members;
    }

    public void setMembers(String[] members){
        if(members == null){
            members = new String[0];
        }
        this.members = members;
    }

This property members can now be used from source code:

    bean.setMembers(new String[]{"Wade Chandler", "Tom Wheeler", "Fabrizio Giudici"});
    bean.setMembers(0, "Wade Chandler");
    String member = bean.getMembers(1);

and in scripting languages supporting the following style:

    String member = bean.members[1];
    bean.members = new String[]{"Wade", "Tom", "Tim"};

todo - write more about indexed properties

What is a property event?

A property event is an event which alerts a listener something of interest has occurred with a property. The standards define two types of property events PropertyChangeEvent and IndexedPropertyChangeEvent for the different property types respectfully. There are two types of listeners defined by the standards which are PropertyChangeListener and VetoableChangeListener.

todo - write more about property events

What is a property descriptor?

What is bean info and did you say bean descriptor?

What is a property editor?

What is a bean customizer?

How do I create editors for properties of simple types as String or primitives?

How do I create editors for properties of more complex types?

How do I display a custom value in my own view in the property sheet? getAsText just isn't working for me.

What if I need an entire UI for customizing my new cool bean?

Yeah yeah, all this talk if fine, any examples?

PersonBean - an example of property editors, bean info, custom components, getAsText, and setAsText

PersonBean - In this example you'll find a top level PersonBean which has some simple String properties and a more complex address property of type AddressBean. PersonBean has a PersonBeanBeanInfo which shows you how to link a property editor and a property together.

The BeanInfo is where AddressBean meets AddressBeanPropertyEditor and AddressBeanEditorPanel. The AddressBeanPropertyEditor and AddressBeanEditorPanel work together to manage properties of type AddressBean. Another important piece of logic to notice is AddressBeanPropertyEditor.getJavaInitializationString(). This is where the property editor gives a Java development environment, such as NetBeans, source code it can use to instantiate and reconfigure an instance of AddressBean to match what you have designed in a bean editor such as NetBean's Matisse user interface designer.

This example was developed in NetBeans 6.5. There are two projects. One is the JavaBean library, PersonBean, which contains PersonBean, AddressBean, and any related classes. The other project named PersonBeanTest uses the PersonBean project. This can be used to see a working example.

Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo