ComboBox Data Binding

Let's create a databound combobox, leveraging MVC in a desktop application.

The result will be a combobox, provided by the NetBeans ChoiceView, that displays data retrieved from a database:


What follows is not much different from the NetBeans Platform CRUD Application Tutorial and you're advised to consult that document if anything that follows isn't clear enough.

One kind of interesting thing about the instructions that follow is that it shows that you're able to create an application where each element of the MVC architecture can be located within a separate module:



Start by creating a new NetBeans Platform application named "MyApplication".

Model

  1. We're going to start by generating JPA entity classes from a database connection. In the New Project wizard, choose "Java Class Library". Click Next. Name the Java Class Library "MyEntities". Click Finish. Right-click the MyEntities project, choose New, and then select "Entity Classes from Database". Work through the wizard, selecting the tables of interest from your database, and naming the package "entities". Click Finish. Now a JPA entity is created for each of the selected tables. In the Project Properties dialog of the project, choose "Copy Dependent Libraries" in the Packaging panel. Build the project. In your project's "dist" folder (visible in the Files window), you'll now see a JAR, together with a "lib" folder that contains the JARs you'll need.

  2. In your NetBeans Platform application, create a module named "MyModel", with code name base "org.my.model". Right-click the project, choose Properties, and in the "Libraries" panel, click Add Dependency button in the Wrapped JARs subtab to add all the JARs from the previous step to the module. Also include "derby-client.jar" or the equivalent driver for your database connection to the module.

Controler

  1. In your NetBeans Platform application, create a module named "MyControler", with code name base "org.my.controler". Right-click the module's Libraries node, in the Projects window, and add a dependency on "Explorer & Property Sheet API".

  2. In the MyControler module, create a class with this content:
    package org.my.controler;
    
    import org.openide.explorer.ExplorerManager;
    
    public class MyUtils {
        
        static  ExplorerManager controler;
    
        public static ExplorerManager getControler() {
            if (controler == null) {
                controler = new ExplorerManager();
            }
            return controler;
        }
        
    }

View

  1. In your NetBeans Platform application, create a module named "MyView", with code name base "org.my.view".  Create a new Window Component, in "explorer" view, for example, let it open on startup, with class name prefix "MyView". Add dependencies on the Nodes API and on the Explorer & Property Sheet API. Also add dependencies on the "MyModel" module and the "MyControler" module. Before doing so, in the "MyModel" module, make the "entities" package and the "javax.persistence" packages public (in the Libraries panel of the Project Properties dialog) and make the one package that you have in the "MyControler" package public too.

  2. Define the top part of the MyViewTopComponent as follows:
    public final class MyViewTopComponent extends TopComponent implements ExplorerManager.Provider {
    
        ExplorerManager controler = MyUtils.getControler();
    
        public MyViewTopComponent() {
    
            initComponents();
    
            setName(Bundle.CTL_MyViewTopComponent());
            setToolTipText(Bundle.HINT_MyViewTopComponent());
    
            setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    
            controler.setRootContext(new AbstractNode(Children.create(new ChildFactory<Customer>() {
                @Override
                protected boolean createKeys(List list) {
                    EntityManager entityManager = Persistence.
                         createEntityManagerFactory("MyEntitiesPU").createEntityManager();
                    Query query = entityManager.createNamedQuery("Customer.findAll");
                    list.addAll(query.getResultList());
                    return true;
                }
                @Override
                protected Node createNodeForKey(Customer key) {
                    Node customerNode = new AbstractNode(
                         Children.LEAF, Lookups.singleton(key));
                    customerNode.setDisplayName(key.getName());
                    return customerNode;
                }
            }, true)));
     
            controler.addPropertyChangeListener(new PropertyChangeListener() {
                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    Customer selectedCustomer = 
                         controler.getSelectedNodes()[0].getLookup().lookup(Customer.class);
                    StatusDisplayer.getDefault().setStatusText(selectedCustomer.getName());
                }
            });
    
            JPanel row1 = new JPanel(new FlowLayout(FlowLayout.LEADING));
            row1.add(new JLabel("Customers: "));
            row1.add(new ChoiceView());
            add(row1);
    
        }
    
        @Override
        public ExplorerManager getExplorerManager() {
            return controler;
        }
    
        ...
        ...
        ...

Now run the application and you'll see the same as the image with which this blog entry started.

The cool thing is that you can add multiple other NetBeans explorer view components together and they'll all be synchronized. Below you see a ListView below a ChoiceView. When an item is selected in the ChoiceView, it is automatically selected in the ListView too, because the two share the same controler:

The reverse is equally true. Select an item in the list and the combobox will automatically be updated with the selected value.

Comments:

Let's say I have a top component to edit Countries with such a ComboBox. How to use DataBindings to select a country in another TopComponent (e.g in a customer form, in the address) ?

Is it possible ?

Posted by guest on June 23, 2012 at 12:02 AM PDT #

Can we bind the Combo Box and List Box to data to perform tasks such as browsing data in a database, entering new data, or editing existing data.

Posted by guest on July 18, 2012 at 04:57 AM PDT #

Very helpful - thx. I want to add a second ChoiceView (for Products) on the same TopComponent. How do I populate the 1st "customer" ChoiceView with customers and the 2nd "products" ChoiceView with products?

Cheers

Posted by nico on July 31, 2012 at 05:14 PM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed
About

Geertjan Wielenga (@geertjanw) is a Principal Product Manager in the Oracle Developer Tools group living & working in Amsterdam. He is a Java technology enthusiast, evangelist, trainer, speaker, and writer. He blogs here daily.

The focus of this blog is mostly on NetBeans (a development tool primarily for Java programmers), with an occasional reference to NetBeans, and sometimes diverging to topics relating to NetBeans. And then there are days when NetBeans is mentioned, just for a change.

Search

Archives
« July 2014
SunMonTueWedThuFriSat
  
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  
       
Today