views:

137

answers:

1

I'm having a brain cramp trying to understand the appropriate way to use JGoodies bindings in my application.

I have a class Article which is a bean that has read-only properties. Article is a "plain" bean, and doesn't manage property listeners, since the properties don't ever change. I have a Swing JPanel which I would like to use to display certain properties of an article. Different Article objects may be viewed at different times.

I'm looking for something (X) which does the following through one or more objects:

  1. X contains the currently viewed Article. I can call X.setArticle() and X.getArticle() to change to a different Article. There is no other way to change the currently viewed Article, I have to go through X so it knows I'm changing it.
  2. When I set up my JPanel, I want to use X to create read-only JTextFields that are bound to various properties of the currently viewed Article (title, authors, etc.)
  3. (this follows from #1 and #2) Anytime X.setArticle() is called, the contents of the text fields will automatically update.

I have tried using BeanAdapter to extract the property models from an Article contained in a ValueHolder, and BasicComponentFactory.createTextField() to create the text fields, and it all seems to work except that I get a com.jgoodies.binding.beans.PropertyUnboundException complaining that my Article class has unbound properties. Duh! I know that, I just can't figure out how to get the right "plumbing" to deal with it. Each Article is unmodifiable, but the currently viewed Article may point to a different one.

any suggestions?

A: 

I figured it out.

I do something like this:

 // on setup:

 BeanAdapter<Article> adapter = new BeanAdapter<Article>((Article)null,
    false);
 // the "false" in the constructor means don't try to observe property
 // changes within the Article, but we still can observe changes
 // if the Article itself is replaced with a new one.

 JTextField tfAuthors = BasicComponentFactory.createTextField(
     adapter.getValueModel("authors"));
 JTextField tfTitle = BasicComponentFactory.createTextField(
     adapter.getValueModel("title"));

Later, when I change the Article object, I just do this:

 public void showArticle(Article article)
 {
     adapter.setBean(article);
 }

and everything updates on screen very nicely.

Jason S