Let a Controller name the ViewModel class and receive it before bindings.

A second View reuses that one instance, and fails the load when it names a different class.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-10-30 18:25:38 +01:00
co-authored by Cursor
parent a89fe47133
commit d26f0c3b21
29 changed files with 1035 additions and 46 deletions
@@ -0,0 +1,193 @@
package de.neitzel.fx.view;
import de.neitzel.fx.view.fixture.Address;
import de.neitzel.fx.view.fixture.Person;
import de.neitzel.injection.ApplicationContext;
import javafx.application.Platform;
import javafx.beans.property.Property;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.net.URL;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
class ChooseControllerAndViewModelTest {
@BeforeAll
static void startJavaFx() throws InterruptedException {
CountDownLatch started = new CountDownLatch(1);
try {
Platform.startup(started::countDown);
} catch (IllegalStateException alreadyStarted) {
started.countDown();
}
if (!started.await(10, TimeUnit.SECONDS)) {
fail("JavaFX toolkit did not start");
}
}
@Test
void labelShowsTheNameRecordedWhenTheViewModelWasHandedOver() throws Exception {
onFx(() -> {
Person person = new Person("Ada");
URL fxml = ChooseControllerAndViewModelTest.class.getResource("handed-name.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen");
LoadedView loaded = ViewLoader.load(fxml, person, context);
Label handedLabel = (Label) loaded.getRoot().lookup("#handedLabel");
assertEquals("handed-Ada", handedLabel.getText());
});
}
@Test
void labelShowsTheGreetingInjectedIntoTheController() throws Exception {
onFx(() -> {
Person person = new Person("Ada");
URL fxml = ChooseControllerAndViewModelTest.class.getResource("desk-greeting.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen");
LoadedView loaded = ViewLoader.load(fxml, person, context);
Label deskLabel = (Label) loaded.getRoot().lookup("#deskLabel");
assertEquals("from-the-desk", deskLabel.getText());
});
}
@Test
void labelShowsTheTitleFromTheNamedViewModel() throws Exception {
onFx(() -> {
Person person = new Person("Ada");
URL fxml = ChooseControllerAndViewModelTest.class.getResource("titled-name.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen");
LoadedView loaded = ViewLoader.load(fxml, person, context);
Label titleLabel = (Label) loaded.getRoot().lookup("#titleLabel");
assertEquals("titled-Ada", titleLabel.getText());
@SuppressWarnings("unchecked")
Property<String> title = (Property<String>) loaded.property("title");
assertNotNull(title);
assertEquals("titled-Ada", title.getValue());
title.setValue("titled-Grace");
assertEquals("titled-Grace", titleLabel.getText());
});
}
@Test
void labelShowsTheBadgeFromAReplacementViewModel() throws Exception {
onFx(() -> {
Person person = new Person("Ada");
URL fxml = ChooseControllerAndViewModelTest.class.getResource("badge-name.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen");
LoadedView loaded = ViewLoader.load(fxml, person, context);
Label badgeLabel = (Label) loaded.getRoot().lookup("#badgeLabel");
assertEquals("badge-Ada", badgeLabel.getText());
@SuppressWarnings("unchecked")
Property<String> badge = (Property<String>) loaded.property("badge");
assertNotNull(badge);
assertEquals("badge-Ada", badge.getValue());
badge.setValue("badge-Grace");
assertEquals("badge-Grace", badgeLabel.getText());
});
}
@Test
void componentLabelShowsTheCaptionFromTheNamedViewModel() throws Exception {
onFx(() -> {
Person person = new Person("Ada");
person.setAddress(new Address("Main"));
URL fxml = ChooseControllerAndViewModelTest.class.getResource("caption-address.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen");
LoadedView loaded = ViewLoader.load(fxml, person, context);
Label captionLabel = (Label) loaded.getRoot().lookup("#captionLabel");
assertEquals("caption-Main", captionLabel.getText());
});
}
@Test
void aLaterViewThatNamesADifferentClassFailsAndLeavesTheFirstView() throws Exception {
onFx(() -> {
Person person = new Person("Ada");
URL titled = ChooseControllerAndViewModelTest.class.getResource("titled-name.fxml");
URL badge = ChooseControllerAndViewModelTest.class.getResource("badge-name.fxml");
assertNotNull(titled);
assertNotNull(badge);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen");
LoadedView first = ViewLoader.load(titled, person, context);
Label titleLabel = (Label) first.getRoot().lookup("#titleLabel");
assertEquals("titled-Ada", titleLabel.getText());
IllegalArgumentException failure = assertThrows(IllegalArgumentException.class,
() -> ViewLoader.load(badge, person, context));
assertTrue(failure.getMessage().contains("TitledViewModel"), failure.getMessage());
assertTrue(failure.getMessage().contains("BadgeViewModel"), failure.getMessage());
assertEquals("titled-Ada", titleLabel.getText());
});
}
@Test
void aLaterViewWithNoAnnotationReusesTheViewModel() throws Exception {
onFx(() -> {
Person person = new Person("Ada");
URL named = ChooseControllerAndViewModelTest.class.getResource("named-person.fxml");
URL plain = ChooseControllerAndViewModelTest.class.getResource("name-both-ways.fxml");
assertNotNull(named);
assertNotNull(plain);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.chosen");
LoadedView first = ViewLoader.load(named, person, context);
LoadedView second = ViewLoader.load(plain, person, context);
TextField firstName = (TextField) first.getRoot().lookup("#nameField");
TextField secondName = (TextField) second.getRoot().lookup("#nameField");
assertEquals("Ada", firstName.getText());
assertEquals("Ada", secondName.getText());
firstName.setText("Grace");
assertEquals("Grace", secondName.getText());
assertEquals("Grace", person.getName());
});
}
private static void onFx(FxAction action) throws Exception {
if (Platform.isFxApplicationThread()) {
action.run();
return;
}
AtomicReference<Throwable> thrown = new AtomicReference<>();
CountDownLatch done = new CountDownLatch(1);
Platform.runLater(() -> {
try {
action.run();
} catch (Throwable failure) {
thrown.set(failure);
} finally {
done.countDown();
}
});
if (!done.await(10, TimeUnit.SECONDS)) {
fail("JavaFX thread did not finish");
}
Throwable failure = thrown.get();
if (failure instanceof Exception exception) {
throw exception;
}
if (failure instanceof Error error) {
throw error;
}
if (failure != null) {
throw new AssertionError(failure);
}
}
@FunctionalInterface
private interface FxAction {
void run() throws Exception;
}
}
@@ -0,0 +1,12 @@
package de.neitzel.fx.view.chosen;
import de.neitzel.fx.view.ViewModelClass;
import jakarta.inject.Singleton;
/**
* Controller that names {@link BadgeViewModel} as a replacement ViewModel.
*/
@Singleton
@ViewModelClass(BadgeViewModel.class)
public class BadgeController {
}
@@ -0,0 +1,33 @@
package de.neitzel.fx.view.chosen;
import de.neitzel.fx.view.fixture.Person;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
* Replacement for the library ViewModel. It exposes a badge property by name and does not
* extend {@link de.neitzel.fx.view.ViewModel}.
*/
public class BadgeViewModel {
private final StringProperty badge = new SimpleStringProperty();
/**
* Builds the replacement and sets the badge from the person's name.
*
* @param model the Model instance
*/
public BadgeViewModel(Object model) {
Person person = (Person) model;
badge.set("badge-" + person.getName());
}
/**
* Returns the badge property a Binding element addresses by name.
*
* @return the badge property
*/
public StringProperty badgeProperty() {
return badge;
}
}
@@ -0,0 +1,44 @@
package de.neitzel.fx.view.chosen;
import de.neitzel.fx.view.ViewModelClass;
import jakarta.inject.Singleton;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.layout.VBox;
/**
* Component that names {@link StreetTitleViewModel} for the address it shows.
*/
@Singleton
@ViewModelClass(StreetTitleViewModel.class)
public class CaptionAddressForm extends VBox {
private final ObjectProperty<Object> model = new SimpleObjectProperty<>(this, "model");
/**
* Returns the model property a parent View sets with a Direct binding.
*
* @return the model property
*/
public ObjectProperty<Object> modelProperty() {
return model;
}
/**
* Returns the address this component shows.
*
* @return the address, or {@code null} when none is set
*/
public Object getModel() {
return model.get();
}
/**
* Sets the address this component shows.
*
* @param model the address
*/
public void setModel(Object model) {
this.model.set(model);
}
}
@@ -0,0 +1,32 @@
package de.neitzel.fx.view.chosen;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
/**
* Controller that shows a greeting supplied by an injected service.
*/
@Singleton
public class DeskController {
private final DeskGreeting greeting;
/**
* Creates a controller that reads its label from the injected greeting.
*
* @param greeting the service that supplies the greeting
*/
@Inject
public DeskController(DeskGreeting greeting) {
this.greeting = greeting;
}
/**
* Returns the greeting from the injected service.
*
* @return the label text
*/
public String deskGreeting() {
return greeting.text();
}
}
@@ -0,0 +1,19 @@
package de.neitzel.fx.view.chosen;
import jakarta.inject.Singleton;
/**
* Service whose text a Controller must show, so a test can see that injection ran.
*/
@Singleton
public class DeskGreeting {
/**
* Returns the greeting written on the label.
*
* @return the greeting
*/
public String text() {
return "from-the-desk";
}
}
@@ -0,0 +1,33 @@
package de.neitzel.fx.view.chosen;
import de.neitzel.fx.view.HasViewModel;
import de.neitzel.fx.view.ViewModel;
import jakarta.inject.Singleton;
/**
* Controller whose computed value is taken from the ViewModel handed over before bindings.
*/
@Singleton
public class HandedNameController implements HasViewModel {
private String handed;
/**
* Records a label value that is available only from the handed ViewModel.
*
* @param viewModel the ViewModel for this View
*/
@Override
public void setViewModel(ViewModel viewModel) {
handed = "handed-" + viewModel.property("name").getValue();
}
/**
* Returns the value recorded when the ViewModel was handed over.
*
* @return the label text
*/
public String handedName() {
return handed;
}
}
@@ -0,0 +1,34 @@
package de.neitzel.fx.view.chosen;
import de.neitzel.fx.view.ViewModel;
import de.neitzel.fx.view.fixture.Address;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
* ViewModel for an address that adds a caption taken from the street.
*/
public class StreetTitleViewModel extends ViewModel {
private final StringProperty caption = new SimpleStringProperty();
/**
* Builds a ViewModel and sets the caption from the address street.
*
* @param model the address
*/
public StreetTitleViewModel(Object model) {
super(model);
Address address = (Address) model;
caption.set("caption-" + address.getStreet());
}
/**
* Returns the caption property a Binding element addresses by name.
*
* @return the caption property
*/
public StringProperty captionProperty() {
return caption;
}
}
@@ -0,0 +1,12 @@
package de.neitzel.fx.view.chosen;
import de.neitzel.fx.view.ViewModelClass;
import jakarta.inject.Singleton;
/**
* Controller that names {@link TitledViewModel} for its View.
*/
@Singleton
@ViewModelClass(TitledViewModel.class)
public class TitledController {
}
@@ -0,0 +1,34 @@
package de.neitzel.fx.view.chosen;
import de.neitzel.fx.view.ViewModel;
import de.neitzel.fx.view.fixture.Person;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
* ViewModel subclass that adds a title property taken from the Model's name.
*/
public class TitledViewModel extends ViewModel {
private final StringProperty title = new SimpleStringProperty();
/**
* Builds a ViewModel and sets the title from the person's name.
*
* @param model the Model instance
*/
public TitledViewModel(Object model) {
super(model);
Person person = (Person) model;
title.set("titled-" + person.getName());
}
/**
* Returns the title property a Binding element addresses by name.
*
* @return the title property
*/
public StringProperty titleProperty() {
return title;
}
}
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<VBox xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml"
fx:controller="de.neitzel.fx.view.chosen.BadgeController">
<fx:define>
<BindingList>
<DirectBinding control="badgeLabel" property="text" path="badge" direction="view"/>
</BindingList>
</fx:define>
<Label fx:id="badgeLabel" id="badgeLabel"/>
</VBox>
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.StackPane?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import de.neitzel.fx.view.chosen.CaptionAddressForm?>
<StackPane xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml">
<fx:define>
<BindingList>
<DirectBinding control="addressForm" property="model" path="address" direction="both"/>
</BindingList>
</fx:define>
<CaptionAddressForm fx:id="addressForm"/>
</StackPane>
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<fx:root type="javafx.scene.layout.VBox" xmlns="http://javafx.com/javafx"
xmlns:fx="http://javafx.com/fxml">
<fx:define>
<BindingList>
<DirectBinding control="captionLabel" property="text" path="caption" direction="view"/>
</BindingList>
</fx:define>
<Label fx:id="captionLabel" id="captionLabel"/>
</fx:root>
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.ComputedBinding?>
<VBox xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml"
fx:controller="de.neitzel.fx.view.chosen.DeskController">
<fx:define>
<BindingList>
<ComputedBinding control="deskLabel" property="text" method="#deskGreeting"/>
</BindingList>
</fx:define>
<Label fx:id="deskLabel" id="deskLabel"/>
</VBox>
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.ComputedBinding?>
<VBox xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml"
fx:controller="de.neitzel.fx.view.chosen.HandedNameController">
<fx:define>
<BindingList>
<ComputedBinding control="handedLabel" property="text" method="#handedName"/>
</BindingList>
</fx:define>
<Label fx:id="handedLabel" id="handedLabel"/>
</VBox>
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.VBox?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<VBox xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml"
fx:controller="de.neitzel.fx.view.chosen.TitledController">
<fx:define>
<BindingList>
<DirectBinding control="nameField" property="text" path="name" direction="both"/>
</BindingList>
</fx:define>
<TextField fx:id="nameField" id="nameField"/>
</VBox>
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<VBox xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml"
fx:controller="de.neitzel.fx.view.chosen.TitledController">
<fx:define>
<BindingList>
<DirectBinding control="titleLabel" property="text" path="title" direction="view"/>
</BindingList>
</fx:define>
<Label fx:id="titleLabel" id="titleLabel"/>
</VBox>