X

Geertjan's Blog

  • January 19, 2011

Create/Register/Initialize JavaBeans in a NetBeans Platform Application

Geertjan Wielenga
Product Manager
You can construct UI components from entries in the layer file, by using the Lookup to read a folder in the registry, and initializing values based on attributes returned via factory methods:
setLayout(new BorderLayout());
Car[] cars = Lookups.forPath("Cars").lookupAll(Car.class).toArray(new Car[0]);
JPanel panel = new JPanel(new MigLayout());
for (Car car : cars) {
String type = car.getType();
panel.add(new JLabel(type+":"));
JTextField yearField = new JTextField();
String year = String.valueOf(car.getYear());
yearField.setText(year);
panel.add(yearField, "wrap");
}
add(panel, BorderLayout.CENTER);

Result of the above:

And this is how you'd register your JavaBeans:

<folder name="Cars">
<file name="org-car-HondaCar.instance">
<attr name="instanceCreate" methodvalue="org.car.HondaCar.factory" />
<attr name="type" stringvalue="Honda"/>
<attr name="year" intvalue="1983"/>
<attr name="position" intvalue="100"/>
</file>
<file name="org-car-MazdaCar.instance">
<attr name="instanceCreate" methodvalue="org.car.MazdaCar.factory" />
<attr name="type" stringvalue="Mazda"/>
<attr name="year" intvalue="1979"/>
<attr name="position" intvalue="200"/>
</file>
</folder>

Each Car registered above implements this interface:

public interface Car {
public String getType();
public int getYear();
}

For example, this is HondaCar:

package org.car;
import java.util.Map;
public class HondaCar implements Car {
String type;
int year;
@Override
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public HondaCar(String type, int year) {
this.type = type;
this.year = year;
}
public static Car factory(Map attrs) {
String type = attrs.get("type").toString();
int year = Integer.parseInt(attrs.get("year").toString());
return new HondaCar(type, year);
}
}

Related reading: http://forums.netbeans.org/post-33219.html

A next step is to create @Car.Registration annotation which you'd use on each of the Car implementations, instead of manually registering them in the layer file.

Join the discussion

Comments ( 1 )
  • Jesse Glick Wednesday, January 19, 2011

    Rather than copying to an array, a little cleaner to just:

    for (Car car : Lookups.forPath("Cars").lookupAll(Car.class)) {...}

    Note that in your example, HondaCar.factory in fact has nothing specific to Hondas in it, which makes the demo a bit confusing.

    Little bit cleaner way to get attributes from an untyped map:

    String type = (String) attrs.get("type");

    int year = (Integer) attrs.get("year");


Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.