JavaFX How to - Create JavaBean for JavaFX








Question

We would like to know how to create JavaBean for JavaFX.

Answer

//  w w  w .  ja  v a  2  s  .  c  om
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ReadOnlyProperty;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

class Book {
  private StringProperty title = new SimpleStringProperty(this, "title",
      "Unknown");
  private DoubleProperty price = new SimpleDoubleProperty(this, "price", 0.0);
  private ReadOnlyStringWrapper ISBN = new ReadOnlyStringWrapper(this, "ISBN",
      "Unknown");

  public Book() {
  }

  public Book(String title, double price, String ISBN) {
    this.title.set(title);
    this.price.set(price);
    this.ISBN.set(ISBN);
  }

  public final String getTitle() {
    return title.get();
  }

  public final void setTitle(String title) {
    this.title.set(title);
  }

  public final StringProperty titleProperty() {
    return title;
  }

  public final double getprice() {
    return price.get();
  }

  public final void setPrice(double price) {
    this.price.set(price);
  }

  public final DoubleProperty priceProperty() {
    return price;
  }

  public final String getISBN() {
    return ISBN.get();
  }

  public final ReadOnlyStringProperty ISBNProperty() {
    return ISBN.getReadOnlyProperty();
  }
}

public class Main {
  public static void main(String[] args) {
    Book book = new Book("Java", 9.99, "9999999999");
    printDetails(book.titleProperty());
    printDetails(book.priceProperty());
    printDetails(book.ISBNProperty());

    book.setTitle("Java 8.0");
    book.setPrice(9.49);

    printDetails(book.titleProperty());
    printDetails(book.priceProperty());
    printDetails(book.ISBNProperty());
  }

  public static void printDetails(ReadOnlyProperty<?> p) {
    String name = p.getName();
    Object value = p.getValue();
    Object bean = p.getBean();
    String beanClassName = (bean == null) ? "null" : bean.getClass()
        .getSimpleName();
    String propClassName = p.getClass().getSimpleName();

    System.out.print(propClassName);
    System.out.print("[Name:" + name);
    System.out.print(", Bean Class:" + beanClassName);
    System.out.println(", Value:" + value + "]");
  }
}