Skip to content

Code JavaFX

Tobias Diez edited this page Dec 11, 2016 · 20 revisions

Architecture: Model - View - (Controller) - View Model (MV(C)VM)

  • View model converts the data from logic and model in a form that is easily usable in the gui.
  • The only purpose of the View is to load and display the fxml file.
  • The Controller initializes the view model and binds it to the view. In an ideal world all the binding would already be done directly in the fxml. But JavaFX's binding expressions are not yet powerful enough to accomplish this.

The only class which uses model and logic classes is the ViewModel. Controller and View only access the ViewModel and never the backend.

An example

View model:

  • The view model should derive from AbstractViewModel.
public class MyDialogViewModel extends AbstractViewModel {
}
  • Add a (readonly) property as a private field and generate the getters:
    private final ReadOnlyStringWrapper heading = new ReadOnlyStringWrapper();

    public ReadOnlyStringProperty headingProperty() {
        return heading.getReadOnlyProperty();
    }

    public String getHeading() {
        return heading.get();
    }
  • Create constructor which initializes the fields to their default values. Write tests to ensure that everything works as expected!
public MyDialogViewModel(Dependency dependency) {
    this.dependency = Objects.requireNonNull(dependency);
    heading.set("Hello " + dependency.getUserName());
}
  • Add methods which allow interaction. Again, don't forget to write tests!
public void shutdown() {
    heading.set("Goodbye!");
}

Controller:

public class AboutDialogController extends AbstractController<AboutDialogViewModel>
@FXML protected Button closeButton;
@FXML protected ImageView iconImage;
@Inject private DialogService dialogService;
@FXML
private void initialize() {
    viewModel = new AboutDialogViewModel(dialogService, clipBoardManager, buildInfo);
}
@FXML
private void openJabrefWebsite() {
    viewModel.openJabrefWebsite();
}

View:

Resources:

Clone this wiki locally