27 Commits
Author SHA1 Message Date
konrad 4022519ab7 Merge NeitzelLib 1.0.8-SNAPSHOT development 2026-11-26 16:12:19 +01:00
konrad 7ec8c45c09 Start NeitzelLib 1.0.8-SNAPSHOT development 2026-11-26 16:12:18 +01:00
konrad 28b3fb1458 Merge NeitzelLib 1.0.7 with optional FX dependency injection 2026-11-26 16:01:48 +01:00
konrad 5759c2295e Prepare NeitzelLib 1.0.7 2026-11-26 16:01:47 +01:00
konrad 20249f5790 Separate JavaFX loading from the Neitzel injection container 2026-11-26 16:01:19 +01:00
konrad efda8c2d14 Merge NeitzelLib 1.0.7-SNAPSHOT development 2026-11-26 12:23:06 +01:00
konrad abfd58b051 Start NeitzelLib 1.0.7-SNAPSHOT development 2026-11-26 12:20:16 +01:00
konrad f585ab9cd9 Merge the Person desk preview release coordinates 2026-11-26 10:41:44 +01:00
konrad 82067cfc1a Use Designer 0.1.0 in the optional Person desk preview 2026-11-26 10:41:43 +01:00
konrad 407ecc28c7 Merge NeitzelLib 1.0.6 release 2026-11-26 10:39:11 +01:00
konrad 0037f089b9 Prepare NeitzelLib 1.0.6 2026-11-26 10:39:11 +01:00
konrad 83e0bdf8d4 Merge literal DataGrid group label keys 2026-11-25 14:49:02 +01:00
konrad 2625616b2f Accept literal group keys in DataGrid column FXML 2026-11-25 13:30:55 +01:00
konrad 9522ed90ce Merge managed FXML views and bindable document inputs 2026-11-24 22:27:05 +01:00
konrad 4a455e63ab Document one-way list replacement in the FX binding guide 2026-11-24 20:52:35 +01:00
konrad e4f1fd3c96 Bind saved HTML and replaceable suggestion catalogues toward the view 2026-11-24 20:49:45 +01:00
konrad 514cc7fb8e Open an independent FXML component in a managed view context 2026-11-24 14:31:31 +01:00
konrad ac992167bc Reconcile read-only FXML binding branch with managed view lifetimes 2026-11-23 19:38:14 +01:00
konrad 50046be154 Land JavaFX test fixtures and 1.0.6-SNAPSHOT development 2026-11-23 19:38:06 +01:00
konrad 597252f676 Merge JavaFX JUnit fixtures and deterministic docking activation test 2026-11-23 19:29:33 +01:00
konrad 073b4a65dc Merge Maven version properties 2026-11-23 19:18:34 +01:00
konrad f1b2fd24d4 Test docking activation independently of desktop focus arbitration
Glass Headless can report both stages focused. On macOS the desktop can deny the input needed to establish the initial focus. Drive both reported window states explicitly with a Stage spy so the real manager must distinguish NoChange from Applied and request focus.
2026-11-23 19:16:45 +01:00
konrad d8b2871f24 Centralize Maven dependency and plugin versions 2026-11-23 19:11:01 +01:00
konrad 7b3f98f489 Provide managed JavaFX fixtures for JUnit Jupiter 2026-11-23 19:01:29 +01:00
konrad e37a66dfa8 Start NeitzelLib 1.0.6-SNAPSHOT development 2026-11-23 18:56:26 +01:00
konrad 081d94e373 Land NeitzelLib 1.0.5 release 2026-11-23 18:55:09 +01:00
konrad 2d12a7d393 Bind named read-only observables toward FXML views 2026-11-23 18:18:45 +01:00
126 changed files with 2074 additions and 794 deletions
+26 -4
View File
@@ -54,13 +54,24 @@ Optional mapped JDBC DataGrid source, initially qualified with H2. See [data-gri
JavaFX docking, saved HTML/SingleFile viewing, standalone bars and optional MVVM bindings from FXML views to ordinary Java models. Docking works with plain JavaFX and standard FXMLLoader without initializing MVVM. See [fx/README.md](fx/README.md) and the [docking guide](fx/docs/docking.md).
### fx-test
JavaFX fixtures for JUnit Jupiter. Add `de.neitzel.lib:fx-test` at the same version as `fx` with Maven scope `test`. Annotate the class with `@FxTest` and accept an `FxFixture` parameter in each test. Use `fx.run` for actions, `fx.call` for values and `fx.await("dialog closed", () -> !dialog.isShowing())` to wait from the test thread. `fx.loadWithDependencies(fxml, model, dependencies)` uses the production ViewLoader and a fresh ViewModelContext per test.
The extension keeps JavaFX running between tests, isolates the class with JUnit's `@Isolated`, hides windows opened by each test, closes its view context and reports unhandled FX callbacks at teardown. Complete background work before the test ends. Select the backend in the test JVM before toolkit startup, for example `-Dglass.platform=Headless`.
### fx-injection
Optional adapter since FX 1.0.7 for applications using Neitzel's `ApplicationContext`.
It brings in `fx` and `injection`. See [adapter setup and migration](fx-injection/README.md).
### injection
Package scanner and type-based container used by `fx`. See [injection/README.md](injection/README.md).
Standalone package scanner and type-based container. See [injection/README.md](injection/README.md).
### fx-example
Person desk that shows how to use `fx` and `injection`. Build with `./mvnw -pl fx-example -am install`, then run `./mvnw -f fx-example/pom.xml javafx:run`. See [fx-example/README.md](fx-example/README.md).
Person desk that shows how to use FX with `fx-injection`. Build with `./mvnw -pl fx-example -am install`, then run `./mvnw -f fx-example/pom.xml javafx:run`. See [fx-example/README.md](fx-example/README.md).
### gson
@@ -84,6 +95,17 @@ The [complete quick start](fx/docs/quick-start.md) includes local installation,
Build with Java 25. Maven wrapper version is 3.9.11; the project requires Maven 3.9.11 or later. Surefire fails the build if tests fail.
## Changes in 1.0.7
- Use `fx` and `fx-test` with an application-supplied `ViewDependencies` adapter.
- Add `fx-injection` to keep using Neitzel's `ApplicationContext` from the new loaders. See [migration](fx-injection/README.md#migrate-an-existing-fx-application).
## Changes in 1.0.6
- Load managed FXML Components independently and bind read-only observables, HTML and replaceable suggestion lists toward the view.
- Use the new `fx-test` module for JavaFX and managed FXML tests with JUnit Jupiter.
- Use literal DataGrid group-label keys in FXML, including file types and paths with spaces.
## Changes in 1.0.5
- Show or hide DataGrid columns from the header checklist or context menu while retaining column order and widths.
@@ -99,7 +121,7 @@ Build with Java 25. Maven wrapper version is 3.9.11; the project requires Maven
## Use a release from Maven
To use release `1.0.5`, add the Gitea registry to the consuming project's POM and use the release
To use release `1.0.7`, add the Gitea registry to the consuming project's POM and use the release
version for the module you need:
```xml
@@ -114,7 +136,7 @@ version for the module you need:
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
<version>1.0.5</version>
<version>1.0.7</version>
</dependency>
</dependencies>
```
+5 -7
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.5</version>
<version>1.0.8-SNAPSHOT</version>
</parent>
<artifactId>core</artifactId>
@@ -18,18 +18,16 @@
<launcher>${project.artifactId}</launcher>
<appName>${project.artifactId}</appName>
<jar.filename>${project.artifactId}-${project.version}</jar.filename>
<!-- Dependency versions -->
<jna.version>5.19.1</jna.version>
</properties>
<dependencies>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.19.1</version>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>${reflections.version}</version>
<version>${jna.version}</version>
</dependency>
</dependencies>
+2 -2
View File
@@ -1,5 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion><parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.5</version></parent>
<modelVersion>4.0.0</modelVersion><parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.8-SNAPSHOT</version></parent>
<artifactId>data-grid-jdbc</artifactId><description>Optional mapped JDBC grid source</description>
<dependencies><dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid</artifactId><version>${project.version}</version></dependency>
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>2.5.252</version><scope>test</scope></dependency></dependencies></project>
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>${h2.version}</version><scope>test</scope></dependency></dependencies></project>
+1 -1
View File
@@ -1,6 +1,6 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.5</version></parent>
<parent><groupId>de.neitzel.lib</groupId><artifactId>neitzellib</artifactId><version>1.0.8-SNAPSHOT</version></parent>
<artifactId>data-grid</artifactId>
<description>Toolkit-independent filter, query and grid setup contracts</description>
</project>
+5 -2
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.5</version>
<version>1.0.8-SNAPSHOT</version>
</parent>
<artifactId>encryption</artifactId>
@@ -18,13 +18,16 @@
<launcher>${project.artifactId}</launcher>
<appName>${project.artifactId}</appName>
<jar.filename>${project.artifactId}-${project.version}</jar.filename>
<!-- Dependency versions -->
<format-preserving-encryption.version>1.0.0</format-preserving-encryption.version>
</properties>
<dependencies>
<dependency>
<groupId>com.idealista</groupId>
<artifactId>format-preserving-encryption</artifactId>
<version>1.0.0</version>
<version>${format-preserving-encryption.version}</version>
</dependency>
</dependencies>
+5 -5
View File
@@ -1,6 +1,6 @@
# Person desk reference application
This runnable application demonstrates [NeitzelLib FX](../fx/README.md) and [injection](../injection/README.md) together. It edits one Person with a home Address, nested Note, visit list, selected visit and tags. Use it as a reference for wiring a real screen; the [minimal quick start](../fx/docs/quick-start.md) is the smaller starting point for a new project.
This runnable application demonstrates [NeitzelLib FX](../fx/README.md) with the [optional Neitzel adapter](../fx-injection/README.md). It edits one Person with a home Address, nested Note, visit list, selected visit and tags. Use it as a reference for wiring a real screen; the [minimal quick start](../fx/docs/quick-start.md) is the smaller starting point for a new project.
Separate Java/FXML launchers demonstrate [standalone bars](../fx/docs/bars.md)
and [docking](../fx/docs/docking.md) without initializing MVVM or injection.
@@ -30,12 +30,12 @@ From the NeitzelLib root with JDK 25:
./mvnw -f fx-example/pom.xml javafx:run
```
The first command installs local `1.0.5` artifacts; the second runs only the application module. Do not combine `javafx:run` with `-am`, since the parent has no JavaFX launcher. See the [quick start](../fx/docs/quick-start.md) for test reports.
The first command installs the checkout’s Maven artifacts; the second runs only the application module. Do not combine `javafx:run` with `-am`, since the parent has no JavaFX launcher. See the [quick start](../fx/docs/quick-start.md) for test reports.
The packaged alternative, after `package` or `install`, is:
```bash
java -jar fx-example/target/fx-example-1.0.5.jar
java -jar fx-example/target/fx-example-1.0.8-SNAPSHOT.jar
```
Keep the adjacent `target/libs` directory with the JAR: the manifest refers to those copied runtime dependencies. A desktop session is required. This example has no `module-info.java`; it is a classpath application.
@@ -47,7 +47,7 @@ Paths below are relative to this module. Java sources share `src/main/java/de/ne
| File/type | Responsibility |
| --- | --- |
| `Main` | Plain Java launcher calling `Application.launch` |
| `DeskApp` | Scan configuration, fresh sample Model, ViewLoader, Scene and message popup registration |
| `DeskApp` | Scan configuration, sample Model, Component registrations in `DeskApp.dependencies(person)`, ViewLoader and window-owned Model context |
| `model/Person`, `Address`, `Note`, `Role` | JavaBean data and enum; no JavaFX properties required |
| `view/DeskController` and `Desk.fxml` | Screen handlers, computed greeting, controls and binding declarations |
| `view/PersonViewModel` | Handwritten ViewModel subclass with a derived title |
@@ -81,7 +81,7 @@ normal build needs no Designer processor; Lombok still runs.
2. Edit Age using its `years ` text format. An invalid value stays visible while the previous Model value is retained. A message explains the failure; a valid value clears that conversion failure.
3. Edit the home street. The path-bound label follows. Empty street input fails through `StreetConverter`; the parent receives the child message with the `home.street` source prefix.
4. Edit the nested note. AddressForm's inner NoteForm binds to its own Model. The `Opened as ...` label records initial setup rather than tracking every later city edit.
5. Add a visit. Both the repeated forms and Table gain a row. Edit a street in one representation and observe the same Address in the other. The Table's Remove button delegates to the controller.
5. Add a visit. Both the repeated forms and Table gain a row. Edit a street in one representation and observe the same Address in the other. The Table's Remove button uses the desk's shared `VisitActions` service.
6. Select a visit in the ComboBox or Table. Both use the `selectedVisit` Attribute. Resize, sort and filter Table columns; filtering and sorting affect displayed rows without reordering the Model's list.
7. Edit the visited date in ISO form (`yyyy-MM-dd`). Invalid text keeps the old date. Add a tag to see a shared ObservableList of simple values.
8. Try the information, warning and fatal message buttons. Severity is data and logging behavior; a fatal message does not itself exit the application. Close each non-blocking popup normally.
+3 -2
View File
@@ -41,8 +41,9 @@ The application adapter owns its change listener and derived bindings. Its
`onClosed` and `onDiscarded` hooks release those resources explicitly. Moves,
collapse and veto do not run those hooks. A rejected factory-created editor is
discarded; rejection of a directly supplied Dockable leaves cleanup to its caller.
This does not dispose the LoadedView or evict the runtime's strong Model-to-ViewModel
identity cache. See the [MVVM lifetime contract](../../fx/docs/architecture.md).
The same hooks close the editor's `ViewModelContext`, which closes the
`LoadedView` and clears its Model-to-ViewModel registrations. See the
[MVVM lifetime contract](../../fx/docs/architecture.md).
`MvvmDockingTest` loads the actual example FXML and checks model/property/control
edits before and after moves, object identity, bar ownership, global toolbar
+1 -1
View File
@@ -6,7 +6,7 @@ From the repository root with JDK 25, build without installing runtime artifacts
```sh
./mvnw -pl fx-example -am package -DskipTests
java -cp 'fx-example/target/fx-example-1.0.5.jar:fx-example/target/libs/*' de.neitzel.fx.example.grid.ProductGridMain
java -cp 'fx-example/target/fx-example-1.0.8-SNAPSHOT.jar:fx-example/target/libs/*' de.neitzel.fx.example.grid.ProductGridMain
```
The default catalog has 10,000 products. Both backends use identical stable IDs, names, categories, quantities and DECIMAL(12,2) prices. Fixtures include duplicate sort values, nulls, empty text, mixed case, Unicode, apostrophes and literal SQL wildcard characters. One `ProductCatalog` service maintains original text and Locale.ROOT comparison keys together on insertion/reset. Mutations run on application workers and explicitly refresh the grid; browsing is read-only.
+1 -1
View File
@@ -5,7 +5,7 @@
After the reactor `verify` or `package` build, from the repository root (no local artifact install required):
```sh
java -cp 'fx-example/target/fx-example-1.0.5.jar:fx-example/target/libs/*' \
java -cp 'fx-example/target/fx-example-1.0.8-SNAPSHOT.jar:fx-example/target/libs/*' \
de.neitzel.fx.example.theme.ThemeGalleryMain
```
+26 -6
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.5</version>
<version>1.0.8-SNAPSHOT</version>
</parent>
<artifactId>fx-example</artifactId>
@@ -18,14 +18,20 @@
<appName>${project.artifactId}</appName>
<main.class>de.neitzel.fx.example.Main</main.class>
<jar.filename>${project.artifactId}-${project.version}</jar.filename>
<!-- Dependency versions -->
<designer.version>0.1.0</designer.version>
<!-- Plugin versions -->
<build.helper.maven.plugin>3.8.0</build.helper.maven.plugin>
</properties>
<dependencies>
<dependency><groupId>de.neitzel.lib</groupId><artifactId>data-grid-jdbc</artifactId><version>${project.version}</version></dependency>
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>2.5.252</version></dependency>
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><version>${h2.version}</version></dependency>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
<artifactId>fx-injection</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
@@ -99,11 +105,25 @@
<profiles>
<profile>
<id>designer-preview</id>
<repositories>
<repository>
<id>gitea-neitzelfxdesigner</id>
<url>https://gitea.neitzel.de/api/packages/konrad/maven</url>
<snapshots><enabled>false</enabled></snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>gitea-neitzelfxdesigner</id>
<url>https://gitea.neitzel.de/api/packages/konrad/maven</url>
<snapshots><enabled>false</enabled></snapshots>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>de.neitzel.fxdesigner</groupId>
<artifactId>designer-preview-api</artifactId>
<version>0.1.0-SNAPSHOT</version>
<version>${designer.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
@@ -112,7 +132,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.8.0</version>
<version>${build.helper.maven.plugin}</version>
<executions>
<execution>
<id>designer-preview-sources</id>
@@ -139,7 +159,7 @@
<path>
<groupId>de.neitzel.fxdesigner</groupId>
<artifactId>designer-model-processor</artifactId>
<version>0.1.0-SNAPSHOT</version>
<version>${designer.version}</version>
</path>
</annotationProcessorPaths>
<compilerArgs>
@@ -2,29 +2,23 @@ package de.neitzel.fx.example.preview;
import de.neitzel.fx.example.DeskApp;
import de.neitzel.fx.example.model.Address;
import de.neitzel.fx.example.view.DeskController;
import de.neitzel.fx.example.view.PersonViewModel;
import de.neitzel.fxdesigner.preview.PreviewProvider;
import de.neitzel.fxdesigner.preview.PreviewSession;
import de.neitzel.injection.ApplicationContext;
import de.neitzel.fx.view.ViewDependencies;
/** Independent samples for the nested, repeated and table-row Address components. */
public final class AddressPreviewProvider implements PreviewProvider<Address, ApplicationContext> {
public final class AddressPreviewProvider implements PreviewProvider<Address, ViewDependencies> {
@Override
public Class<Address> modelType() {
return Address.class;
}
@Override
public PreviewSession<Address, ApplicationContext> open(String id) {
public PreviewSession<Address, ViewDependencies> open(String id) {
if (!java.util.Set.of("address", "visit", "row").contains(id))
throw new IllegalArgumentException("Unknown address example: " + id);
var person = DeskApp.sample();
var context = new ApplicationContext(DeskApp.class);
// An independently previewed row still needs the parent action's state.
// No Desk.fxml is loaded and no popup listener is installed.
if ("row".equals(id))
context.getComponent(DeskController.class).setViewModel(new PersonViewModel(person));
var context = DeskApp.dependencies(person);
return new SampleSession<>(
"address".equals(id) ? person.getHome() : person.getVisits().getFirst(), context);
}
@@ -4,18 +4,19 @@ import de.neitzel.fx.example.DeskApp;
import de.neitzel.fx.example.model.Person;
import de.neitzel.fxdesigner.preview.PreviewProvider;
import de.neitzel.fxdesigner.preview.PreviewSession;
import de.neitzel.injection.ApplicationContext;
import de.neitzel.fx.view.ViewDependencies;
/** Optional test-source preview adapter; it never enters the application distribution. */
public final class DeskPreviewProvider implements PreviewProvider<Person, ApplicationContext> {
public final class DeskPreviewProvider implements PreviewProvider<Person, ViewDependencies> {
@Override
public Class<Person> modelType() {
return Person.class;
}
@Override
public PreviewSession<Person, ApplicationContext> open(String id) {
public PreviewSession<Person, ViewDependencies> open(String id) {
if (!"desk".equals(id)) throw new IllegalArgumentException("Unknown desk example: " + id);
return new SampleSession<>(DeskApp.sample(), new ApplicationContext(DeskApp.class));
var person = DeskApp.sample();
return new SampleSession<>(person, DeskApp.dependencies(person));
}
}
@@ -4,19 +4,19 @@ import de.neitzel.fx.example.DeskApp;
import de.neitzel.fx.example.model.Note;
import de.neitzel.fxdesigner.preview.PreviewProvider;
import de.neitzel.fxdesigner.preview.PreviewSession;
import de.neitzel.injection.ApplicationContext;
import de.neitzel.fx.view.ViewDependencies;
/** Independent sample for the nested note editor. */
public final class NotePreviewProvider implements PreviewProvider<Note, ApplicationContext> {
public final class NotePreviewProvider implements PreviewProvider<Note, ViewDependencies> {
@Override
public Class<Note> modelType() {
return Note.class;
}
@Override
public PreviewSession<Note, ApplicationContext> open(String id) {
public PreviewSession<Note, ViewDependencies> open(String id) {
if (!"note".equals(id)) throw new IllegalArgumentException("Unknown note example: " + id);
return new SampleSession<>(
DeskApp.sample().getHome().getNote(), new ApplicationContext(DeskApp.class));
var person = DeskApp.sample();
return new SampleSession<>(person.getHome().getNote(), DeskApp.dependencies(person));
}
}
@@ -3,7 +3,9 @@ package de.neitzel.fx.example.preview;
import static org.junit.jupiter.api.Assertions.*;
import de.neitzel.fx.example.view.DeskController;
import de.neitzel.fx.example.view.VisitRow;
import de.neitzel.fx.view.ViewLoader;
import de.neitzel.fx.view.ViewModelContext;
import javafx.application.Platform;
@@ -48,12 +50,12 @@ class PreviewProvidersTest {
assertNotSame(first.model(), second.model());
assertNotSame(first.model().getHome(), second.model().getHome());
assertNotSame(first.context(), second.context());
var view =
ViewLoader.load(
DeskController.class.getResource("Desk.fxml"),
first.model(),
first.context());
assertNotNull(view.getRoot().lookup("#nameField"));
try (var models = new ViewModelContext()) {
var view = ViewLoader.loadWithDependencies(
DeskController.class.getResource("Desk.fxml"),
first.model(), first.context(), models);
assertNotNull(view.getRoot().lookup("#nameField"));
}
assertEquals("Ada Lovelace", first.model().getName());
assertTrue(first.ready().toCompletableFuture().isDone());
assertThrows(IllegalArgumentException.class, () -> provider.open("unknown"));
@@ -70,11 +72,11 @@ class PreviewProvidersTest {
var visit = addresses.open("visit");
assertNotNull(visit.model().getVisitedOn());
var row = addresses.open("row");
assertDoesNotThrow(
() ->
row.context()
.getComponent(DeskController.class)
.removeVisit(row.model()));
try (var models = new ViewModelContext()) {
var view = ViewLoader.loadComponentWithDependencies(
VisitRow.class, row.model(), row.context(), models);
assertDoesNotThrow(((VisitRow) view.getRoot())::remove);
}
var note = new NotePreviewProvider().open("note");
assertEquals("Kept at home", note.model().getText());
assertThrows(IllegalArgumentException.class, () -> addresses.open("desk"));
@@ -1,11 +1,11 @@
package de.neitzel.fx.example.preview;
import de.neitzel.fxdesigner.preview.PreviewSession;
import de.neitzel.injection.ApplicationContext;
import de.neitzel.fx.view.ViewDependencies;
/** The sample owns no timers, network connections or background work to release. */
record SampleSession<M>(M model, ApplicationContext context)
implements PreviewSession<M, ApplicationContext> {
record SampleSession<M>(M model, ViewDependencies context)
implements PreviewSession<M, ViewDependencies> {
@Override
public void close() {}
}
@@ -4,19 +4,28 @@ import de.neitzel.fx.example.model.Address;
import de.neitzel.fx.example.model.Note;
import de.neitzel.fx.example.model.Person;
import de.neitzel.fx.example.model.Role;
import de.neitzel.fx.example.view.AddressForm;
import de.neitzel.fx.example.view.DeskController;
import de.neitzel.fx.example.view.NoteForm;
import de.neitzel.fx.example.view.VisitActions;
import de.neitzel.fx.example.view.VisitForm;
import de.neitzel.fx.example.view.VisitRow;
import de.neitzel.fx.injection.NeitzelViewDependencies;
import de.neitzel.fx.view.LoadedView;
import de.neitzel.fx.view.MessagePopup;
import de.neitzel.fx.view.ViewLoader;
import de.neitzel.fx.view.ViewModelContext;
import de.neitzel.injection.ApplicationContext;
import de.neitzel.injection.annotation.Config;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* Opens the person desk for one ordinary {@link Person}.
@@ -60,6 +69,14 @@ public class DeskApp extends Application {
return person;
}
/** Configures one Model and shared service context for the app or a preview. */
public static NeitzelViewDependencies dependencies(Person person) {
var context = new ApplicationContext(DeskApp.class);
context.getComponent(VisitActions.class).setPerson(person);
return new NeitzelViewDependencies(context,
Set.of(AddressForm.class, NoteForm.class, VisitForm.class, VisitRow.class));
}
/**
* Launches the desk.
*
@@ -76,9 +93,11 @@ public class DeskApp extends Application {
*/
@Override
public void start(Stage stage) {
ApplicationContext context = new ApplicationContext(DeskApp.class);
Person person = sample();
LoadedView loaded = ViewLoader.load(DeskController.class.getResource("Desk.fxml"), person, context);
var models = new ViewModelContext();
LoadedView loaded = ViewLoader.loadWithDependencies(
DeskController.class.getResource("Desk.fxml"), person, dependencies(person), models);
stage.addEventHandler(WindowEvent.WINDOW_HIDDEN, event -> models.close());
MessagePopup.showNewMessages(loaded.getViewModel());
stage.setTitle("fx example");
stage.setScene(new Scene(loaded.getRoot()));
@@ -3,9 +3,12 @@ package de.neitzel.fx.example.docking.mvvm;
import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.example.model.Note;
import de.neitzel.fx.injection.NeitzelViewDependencies;
import de.neitzel.fx.view.LoadedView;
import de.neitzel.fx.view.ViewLoader;
import de.neitzel.fx.view.ViewModelContext;
import de.neitzel.injection.ApplicationContext;
import java.util.Set;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.StringBinding;
import javafx.beans.property.Property;
@@ -21,6 +24,7 @@ import lombok.Getter;
/** Application adapter: one loaded View becomes ordinary Dockable content. */
public final class MvvmEditor implements AutoCloseable {
@Getter private final Note model = new Note("Edit this note, then move or float its tab.");
private final ViewModelContext models = new ViewModelContext();
@Getter private final LoadedView view;
@Getter private final Dockable dockable;
private final Property<String> text;
@@ -35,8 +39,9 @@ public final class MvvmEditor implements AutoCloseable {
@SuppressWarnings("unchecked")
public MvvmEditor(String id) {
view = ViewLoader.load(MvvmEditor.class.getResource("MvvmEditor.fxml"), model,
new ApplicationContext(MvvmEditor.class));
var dependencies = new NeitzelViewDependencies(new ApplicationContext(MvvmEditor.class), Set.of());
view = ViewLoader.loadWithDependencies(
MvvmEditor.class.getResource("MvvmEditor.fxml"), model, dependencies, models);
text = (Property<String>) view.property("text");
TextArea input = (TextArea) view.getRoot().lookup("#text");
dockable = new Dockable(new DockableId(id), view.getRoot());
@@ -64,7 +69,7 @@ public final class MvvmEditor implements AutoCloseable {
dirty.set(false);
}
/** Releases this adapter's resources, not the LoadedView or global ViewModel identity cache. */
/** Releases the editor's bindings and its managed View. */
@Override public void close() {
if (released) return;
released = true;
@@ -76,5 +81,6 @@ public final class MvvmEditor implements AutoCloseable {
status.setText("Released application listeners");
clear.setOnAction(null);
clear.setDisable(true);
models.close();
}
}
@@ -95,18 +95,6 @@ public class DeskController implements HasViewModel {
visits().add(created);
}
/**
* Removes a visit from the list the table and Repeat are watching.
*
* @param visit the visit
*/
public void removeVisit(Address visit) {
if (visit == null) {
return;
}
visits().remove(visit);
}
/**
* Adds the tag field's text to the tag list and clears the field.
*/
@@ -0,0 +1,17 @@
package de.neitzel.fx.example.view;
import de.neitzel.fx.example.model.Address;
import de.neitzel.fx.example.model.Person;
import jakarta.inject.Singleton;
import lombok.Setter;
/** Removes a visit from the Model that owns the repeated forms and table rows. */
@Singleton
public final class VisitActions {
@Setter
private Person person;
public void remove(Address visit) {
person.getVisits().remove(visit);
}
}
@@ -21,9 +21,9 @@ import lombok.RequiredArgsConstructor;
public class VisitRow extends HBox {
/**
* The desk controller that removes a visit from the person.
* The shared action that removes a visit from the person.
*/
private final DeskController desk;
private final VisitActions visits;
/**
* The visit this row edits. The table sets it once.
@@ -63,7 +63,7 @@ public class VisitRow extends HBox {
@FXML
public void remove() {
if (getModel() instanceof Address address) {
desk.removeVisit(address);
visits.remove(address);
}
}
}
@@ -9,7 +9,8 @@ import de.neitzel.fx.example.view.VisitForm;
import de.neitzel.fx.example.view.VisitRow;
import de.neitzel.fx.view.LoadedView;
import de.neitzel.fx.view.ViewLoader;
import de.neitzel.injection.ApplicationContext;
import de.neitzel.fx.view.ViewDependencies;
import de.neitzel.fx.view.ViewModelContext;
import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.Parent;
@@ -122,16 +123,13 @@ class DeskLoadsTest {
/**
* A second view of the same person reuses the view model, so a name edit shows on both.
* <p>
* The second document is only a name field. Loading the desk again would rebuild the home
* address form, and that form is the cached singleton already showing.
*/
@Test
void secondViewReusesTheViewModel() throws Exception {
onFx(() -> {
Loaded first = load();
LoadedView second = ViewLoader.load(
DeskLoadsTest.class.getResource("NameLine.fxml"), first.person(), first.context());
LoadedView second = ViewLoader.loadWithDependencies(
DeskLoadsTest.class.getResource("NameLine.fxml"), first.person(), first.context(), first.models());
assertSame(first.view().getViewModel(), second.getViewModel());
textField(first.root(), "nameField").setText("Grace");
assertEquals("Grace", first.person().getName());
@@ -261,16 +259,15 @@ class DeskLoadsTest {
onFx(() -> {
Loaded loaded = load();
Parent root = loaded.root();
DeskController desk = loaded.context().getComponent(DeskController.class);
desk.leaveNote();
fire(root, "Leave a note");
assertEquals(de.neitzel.fx.view.Message.Severity.INFO,
loaded.view().getViewModel().getLatestMessage().getSeverity());
assertEquals("The model already has the name Ada Lovelace.", text(root, "noticeLabel"));
desk.leaveWarning();
fire(root, "Leave a warning");
assertEquals(de.neitzel.fx.view.Message.Severity.WARN,
loaded.view().getViewModel().getLatestMessage().getSeverity());
assertEquals("Check the age before leaving the desk.", text(root, "noticeLabel"));
desk.leaveFatal();
fire(root, "Leave a fatal notice");
assertEquals(de.neitzel.fx.view.Message.Severity.FATAL,
loaded.view().getViewModel().getLatestMessage().getSeverity());
assertEquals("The desk cannot store this person.", text(root, "noticeLabel"));
@@ -300,9 +297,10 @@ class DeskLoadsTest {
*
* @param person the model
* @param view the loaded view
* @param context the container
* @param context the adapter
* @param models the ViewModel context
*/
private record Loaded(Person person, LoadedView view, ApplicationContext context) {
private record Loaded(Person person, LoadedView view, ViewDependencies context, ViewModelContext models) {
/**
* Returns the scene-graph root.
@@ -321,9 +319,16 @@ class DeskLoadsTest {
*/
private static Loaded load() {
Person person = DeskApp.sample();
ApplicationContext context = new ApplicationContext(DeskApp.class);
LoadedView view = ViewLoader.load(DeskController.class.getResource("Desk.fxml"), person, context);
return new Loaded(person, view, context);
var context = DeskApp.dependencies(person);
var models = new ViewModelContext();
var view = ViewLoader.loadWithDependencies(
DeskController.class.getResource("Desk.fxml"), person, context, models);
return new Loaded(person, view, context, models);
}
private static void fire(Parent root, String text) {
root.lookupAll(".button").stream().filter(Button.class::isInstance).map(Button.class::cast)
.filter(button -> text.equals(button.getText())).findFirst().orElseThrow().fire();
}
/**
+64
View File
@@ -0,0 +1,64 @@
# Neitzel DI adapter for FX
The adapter is available from NeitzelLib 1.0.7. See the
[Maven repository setup](../README.md#use-a-release-from-maven). For a
local source build, run `./mvnw -pl fx-injection -am install` from the
NeitzelLib root with JDK 25 and the application’s Maven repository.
```xml
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx-injection</artifactId>
<version>1.0.7</version>
</dependency>
```
Use the same version for all NeitzelLib modules. The adapter resolves `fx`,
`injection` and its scanner dependencies. Applications with their own
`ViewDependencies` can depend on `fx` directly.
Import the adapter from `de.neitzel.fx.injection`, the container from
`de.neitzel.injection` and the loader and Model context from
`de.neitzel.fx.view`.
```java
var services = new ApplicationContext(MyApplication.class);
var dependencies = new NeitzelViewDependencies(services, Set.of(AddressForm.class, VisitRow.class));
var models = new ViewModelContext();
var view = ViewLoader.loadWithDependencies(fxml, model, dependencies, models);
stage.setScene(new Scene(view.getRoot()));
stage.addEventHandler(WindowEvent.WINDOW_HIDDEN, event -> models.close());
```
The registration set contains the exact FXML Component classes, including
those used by Repeat and Table. The adapter asks the context for a fresh
controller or Component and gives FX the corresponding release action.
The release action closes UI instances that implement `AutoCloseable`.
Converters and Localizer come from the context's ordinary lookup. The adapter
reports a missing service as an empty result and propagates lookup or
creation errors. The application owns the context and its shared services.
The JPMS module name is `de.neitzel.fx.injection`. Named applications
keep the package access needed by FXML and Neitzel's package scanner.
Declare `requires de.neitzel.fx.injection` for the adapter and `requires fx` and
`requires injection` for their directly imported types. The Neitzel package
scanner still needs access to its scanned packages in named applications.
## Migrate an existing FX application
Use `ViewLoader.loadWithDependencies(..., dependencies, models)`,
`ViewLoader.loadComponentWithDependencies(..., dependencies, models)`,
and `FxFixture.loadWithDependencies(..., dependencies)` for the new
FX artifacts. Replace the previous public `ApplicationContext` loader
calls and recompile. Retain the Model context with its window or
dockable and close it when that owner ends. Each View load gets its own
controller and Components. If a row previously called a cached controller,
inject the shared action it needs. The [Person Desk](../fx-example/README.md)
does this with `VisitActions`.
A Designer provider on the new artifacts returns the configured adapter
from `PreviewSession.context()` and declares `ViewDependencies` as its
context type. Existing providers returning `ApplicationContext` continue to
run with compatible older FX artifacts such as 1.0.6. Consumers of the standalone
[Neitzel injection container](../injection/README.md) can keep using its
existing API.
+54
View File
@@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.8-SNAPSHOT</version>
</parent>
<artifactId>fx-injection</artifactId>
<dependencies>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>injection</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx-test</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestEntries>
<Automatic-Module-Name>de.neitzel.fx.injection</Automatic-Module-Name>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<glass.platform>Headless</glass.platform>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,53 @@
package de.neitzel.fx.injection;
import de.neitzel.fx.view.ViewDependencies;
import de.neitzel.fx.view.ViewObject;
import de.neitzel.injection.ApplicationContext;
import de.neitzel.injection.MissingComponentException;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/** Connects managed FX Views to an application-owned Neitzel injection context. */
public record NeitzelViewDependencies(ApplicationContext context, Set<Class<?>> components)
implements ViewDependencies {
/** Creates an adapter with the concrete classes used as FXML Components and rows. */
public NeitzelViewDependencies {
Objects.requireNonNull(context, "Application context");
components = Set.copyOf(components);
}
@Override
public boolean isComponent(Class<?> type) {
return components.contains(type);
}
@Override
public <T> Optional<T> findService(Class<T> type) {
try {
return Optional.of(context.getComponent(type));
} catch (MissingComponentException missing) {
if (missing.getComponentType() == type) return Optional.empty();
throw missing;
}
}
@Override
public <T> ViewObject<T> createViewObject(Class<T> type) {
T instance = context.createComponent(type);
return new ViewObject<>(instance, () -> release(instance));
}
private static void release(Object instance) {
if (instance instanceof AutoCloseable closeable) {
try {
closeable.close();
} catch (RuntimeException failure) {
throw failure;
} catch (Exception failure) {
throw new IllegalStateException("Could not close " + instance.getClass().getName(), failure);
}
}
}
}
@@ -0,0 +1,126 @@
package de.neitzel.fx.injection;
import de.neitzel.fx.i18n.Localizer;
import de.neitzel.fx.injection.fixture.Card;
import de.neitzel.fx.injection.fixture.Controller;
import de.neitzel.fx.injection.fixture.Entry;
import de.neitzel.fx.injection.fixture.Lifecycle;
import de.neitzel.fx.test.FxFixture;
import de.neitzel.fx.test.FxTest;
import de.neitzel.fx.view.ViewLoader;
import de.neitzel.fx.view.ViewModelContext;
import de.neitzel.injection.ApplicationContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.VBox;
import lombok.Getter;
import lombok.Setter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
@FxTest
class NeitzelViewDependenciesTest {
@Getter
@Setter
public static final class Model {
private String name = "Ada";
private List<Entry> entries = new ArrayList<>(List.of(new Entry()));
}
@Test
void loadsRepeatTableAndStandaloneComponentWithOneApplicationContext(FxFixture fx) throws Exception {
fx.run(() -> {
var context = new ApplicationContext(Controller.class);
var lifecycle = context.getComponent(Lifecycle.class);
context.addSingleton(Localizer.class, new Localizer(Locale.ENGLISH, Locale.ENGLISH,
new Localizer.Catalog(Controller.class, "View")));
var dependencies = new NeitzelViewDependencies(context, Set.of(Card.class));
var cached = context.getComponent(Card.class);
assertSame(cached, context.getComponent(VBox.class));
assertFalse(dependencies.isComponent(VBox.class));
try (var models = new ViewModelContext()) {
var model = new Model();
var fxml = Controller.class.getResource("View.fxml");
var first = ViewLoader.loadWithDependencies(fxml, model, dependencies, models);
var second = ViewLoader.loadWithDependencies(fxml, new Model(), dependencies, models);
assertEquals(VBox.class, first.getRoot().getClass());
var caption = (Label) first.getRoot().lookup("#caption");
assertEquals("[Ada]", caption.getText());
assertEquals("Localized", caption.getAccessibleText());
var controller = (Controller) caption.getUserData();
var other = (Controller) second.getRoot().lookup("#caption").getUserData();
assertNotSame(controller, other);
assertSame(lifecycle, controller.getLifecycle());
assertSame(lifecycle, other.getLifecycle());
var embedded = (Card) first.getRoot().lookup("#card");
var repeated = (Card) ((VBox) first.getRoot().lookup("#repeat")).getChildren().getFirst();
var table = first.getRoot().lookup("#table");
var rows = (VBox) ((ScrollPane) table.lookup(".table-scroll")).getContent();
var row = (Card) rows.getChildren().getFirst();
assertNotSame(cached, embedded);
assertNotSame(embedded, repeated);
assertNotSame(repeated, row);
model.getEntries().clear();
assertEquals(1, lifecycle.closeCount(repeated));
assertEquals(1, lifecycle.closeCount(row));
var separate = ViewLoader.loadComponentWithDependencies(Card.class, new Entry(), dependencies, models);
assertEquals("Ada", ((Label) separate.getRoot().lookup("#name")).getText());
separate.close();
assertEquals(1, lifecycle.closeCount(separate.getRoot()));
first.close();
first.close();
assertEquals(1, lifecycle.closeCount(embedded));
assertEquals(1, lifecycle.closeCount(controller));
assertEquals(0, lifecycle.closeCount(other));
assertSame(cached, context.getComponent(Card.class));
}
});
}
@Test
void rollsBackAndDistinguishesMissingServicesFromOverrides(FxFixture fx) throws Exception {
fx.run(() -> {
var failedLookup = new IllegalArgumentException("Lookup override failed");
var context = new ApplicationContext(Controller.class) {
@Override
public <T> T getComponent(Class<? extends T> type) {
if (type == String.class) return type.cast("override");
if (type == Integer.class) throw failedLookup;
return super.getComponent(type);
}
};
var dependencies = new NeitzelViewDependencies(context, Set.of(Card.class));
assertTrue(dependencies.findService(Localizer.class).isEmpty());
assertEquals("override", dependencies.findService(String.class).orElseThrow());
assertSame(failedLookup, assertThrows(IllegalArgumentException.class,
() -> dependencies.findService(Integer.class)));
var acquired = new ArrayList<>();
var tracking = new de.neitzel.fx.view.ViewDependencies() {
public boolean isComponent(Class<?> type) { return dependencies.isComponent(type); }
public <T> java.util.Optional<T> findService(Class<T> type) {
return dependencies.findService(type);
}
public <T> de.neitzel.fx.view.ViewObject<T> createViewObject(Class<T> type) {
var found = dependencies.createViewObject(type);
acquired.add(found.instance());
return found;
}
};
try (var models = new ViewModelContext()) {
assertThrows(IllegalStateException.class, () -> ViewLoader.loadWithDependencies(
Controller.class.getResource("Invalid.fxml"), new Model(), tracking, models));
}
var lifecycle = context.getComponent(Lifecycle.class);
assertEquals(2, acquired.size());
assertTrue(acquired.stream().allMatch(value -> lifecycle.closeCount(value) == 1));
});
}
}
@@ -0,0 +1,28 @@
package de.neitzel.fx.injection.fixture;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.layout.VBox;
@Singleton
public final class Card extends VBox implements AutoCloseable {
private final Lifecycle lifecycle;
private final ObjectProperty<Entry> model = new SimpleObjectProperty<>(this, "model");
@Inject
public Card(Lifecycle lifecycle) {
this.lifecycle = lifecycle;
lifecycle.opened(this);
}
public ObjectProperty<Entry> modelProperty() { return model; }
public Entry getModel() { return model.get(); }
public void setModel(Entry entry) { model.set(entry); }
@Override
public void close() { lifecycle.closed(this); }
}
@@ -0,0 +1,32 @@
package de.neitzel.fx.injection.fixture;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import javafx.scene.control.Label;
import javafx.fxml.FXML;
import lombok.Getter;
@Singleton
public final class Controller implements AutoCloseable {
@Getter
private final Lifecycle lifecycle;
@FXML
private Label caption;
@Inject
public Controller(Lifecycle lifecycle) {
this.lifecycle = lifecycle;
lifecycle.opened(this);
}
@FXML
private void initialize() {
caption.setUserData(this);
}
@Override
public void close() {
lifecycle.closed(this);
}
}
@@ -0,0 +1,12 @@
package de.neitzel.fx.injection.fixture;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@RequiredArgsConstructor
public final class Entry {
private String name = "Ada";
}
@@ -0,0 +1,13 @@
package de.neitzel.fx.injection.fixture;
import de.neitzel.fx.view.Converter;
import jakarta.inject.Singleton;
@Singleton
public final class FormatName implements Converter {
@Override
public Object toControlValue(Object value) { return "[" + value + "]"; }
@Override
public Object toAttributeValue(Object value) { return value; }
}
@@ -0,0 +1,16 @@
package de.neitzel.fx.injection.fixture;
import jakarta.inject.Singleton;
import java.util.IdentityHashMap;
import java.util.Map;
@Singleton
public final class Lifecycle {
private final Map<Object, Integer> counts = new IdentityHashMap<>();
public void opened(Object instance) { counts.put(instance, 0); }
public void closed(Object instance) { counts.computeIfPresent(instance, (key, count) -> count + 1); }
public int closeCount(Object instance) { return counts.get(instance); }
}
@@ -0,0 +1,10 @@
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<fx:root type="javafx.scene.layout.VBox" xmlns:fx="http://javafx.com/fxml/1">
<fx:define>
<BindingList><DirectBinding control="name" property="text" path="name" direction="view"/></BindingList>
</fx:define>
<Label fx:id="name"/>
</fx:root>
@@ -0,0 +1,7 @@
<?import de.neitzel.fx.injection.fixture.Card?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.neitzel.fx.injection.fixture.Controller">
<Label fx:id="caption"/>
<Card unknownProperty="fails after acquisition"/>
</VBox>
@@ -0,0 +1,23 @@
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.Column?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import de.neitzel.fx.view.Repeat?>
<?import de.neitzel.fx.view.Table?>
<?import de.neitzel.fx.injection.fixture.Card?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.VBox?>
<VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="de.neitzel.fx.injection.fixture.Controller">
<fx:define>
<BindingList>
<DirectBinding control="caption" property="text" path="name" direction="view"
converter="de.neitzel.fx.injection.fixture.FormatName"/>
<Repeat pane="repeat" collection="entries" component="de.neitzel.fx.injection.fixture.Card"/>
</BindingList>
</fx:define>
<Label fx:id="caption" accessibleText="%view.caption"/>
<Card fx:id="card"/>
<VBox fx:id="repeat"/>
<Table fx:id="table" collection="entries" row="de.neitzel.fx.injection.fixture.Card">
<Column header="Name" attribute="name"/>
</Table>
</VBox>
@@ -0,0 +1 @@
view.caption=Localized
+37
View File
@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.8-SNAPSHOT</version>
</parent>
<artifactId>fx-test</artifactId>
<dependencies>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<glass.platform>Headless</glass.platform>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,37 @@
package de.neitzel.fx.test;
import java.lang.reflect.Method;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolver;
final class FxExtension implements BeforeEachCallback, AfterEachCallback, ParameterResolver {
private static final ExtensionContext.Namespace NAMESPACE = ExtensionContext.Namespace.create(FxExtension.class);
@Override
public void beforeEach(ExtensionContext context) throws Exception {
var fixture = new FxFixture();
fixture.start();
context.getStore(NAMESPACE).put(FxFixture.class, fixture);
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
var fixture = context.getStore(NAMESPACE).remove(FxFixture.class, FxFixture.class);
if (fixture != null) fixture.finish();
}
@Override
public boolean supportsParameter(ParameterContext parameter, ExtensionContext context) {
return parameter.getParameter().getType() == FxFixture.class
&& parameter.getDeclaringExecutable() instanceof Method
&& context.getStore(NAMESPACE).get(FxFixture.class) != null;
}
@Override
public Object resolveParameter(ParameterContext parameter, ExtensionContext context) {
return context.getStore(NAMESPACE).get(FxFixture.class, FxFixture.class);
}
}
@@ -0,0 +1,140 @@
package de.neitzel.fx.test;
import de.neitzel.fx.view.LoadedView;
import de.neitzel.fx.view.ViewDependencies;
import de.neitzel.fx.view.ViewLoader;
import de.neitzel.fx.view.ViewModelContext;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BooleanSupplier;
import javafx.application.Platform;
import javafx.stage.Window;
/** JavaFX test operations scoped to one JUnit test. Obtain the fixture through {@link FxTest}. */
public final class FxFixture {
private static final long TIMEOUT_SECONDS = 10;
private final ViewModelContext models = new ViewModelContext();
private final List<Throwable> callbackFailures = new ArrayList<>();
private List<Window> previousWindows;
private Thread.UncaughtExceptionHandler previousHandler;
/** An FX-thread action that may propagate a checked exception. */
@FunctionalInterface
public interface Action {
/**
* Performs the action.
* @throws Exception on failure
*/
void run() throws Exception;
}
FxFixture() {}
void start() throws Exception {
try {
Platform.startup(() -> {});
} catch (IllegalStateException alreadyStarted) {
// A previous test or another JavaFX client has started this JVM's toolkit.
}
run(() -> {
Platform.setImplicitExit(false);
previousWindows = List.copyOf(Window.getWindows());
previousHandler = Thread.currentThread().getUncaughtExceptionHandler();
Thread.currentThread().setUncaughtExceptionHandler((thread, error) -> callbackFailures.add(error));
});
}
/**
* Runs an action on the FX thread and propagates its failure to the test.
* @param action test action
* @throws Exception if the action fails or the wait is interrupted or times out
*/
public void run(Action action) throws Exception {
call(() -> {
action.run();
return null;
});
}
/**
* Returns the result of an FX-thread operation, with a bounded wait on the calling thread.
* @param <T> result type
* @param action operation to perform
* @return the value returned by the operation
* @throws Exception if the operation fails or the wait is interrupted or times out
*/
public <T> T call(Callable<T> action) throws Exception {
if (Platform.isFxApplicationThread()) return action.call();
var task = new FutureTask<>(action);
Platform.runLater(task);
try {
return task.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (ExecutionException failure) {
if (failure.getCause() instanceof Exception exception) throw exception;
if (failure.getCause() instanceof Error error) throw error;
throw new AssertionError(failure.getCause());
} catch (TimeoutException | InterruptedException failure) {
task.cancel(false);
throw failure;
}
}
/**
* Waits on the test thread while evaluating the named condition on the FX thread.
* @param description expected state, included in the timeout message
* @param condition UI predicate to evaluate
* @throws Exception if evaluation fails or waiting is interrupted
* @throws AssertionError if the condition stays false
*/
public void await(String description, BooleanSupplier condition) throws Exception {
if (Platform.isFxApplicationThread()) throw new IllegalStateException("await requires the test thread");
long start = System.nanoTime();
while (!call(condition::getAsBoolean)) {
if (System.nanoTime() - start >= TimeUnit.SECONDS.toNanos(TIMEOUT_SECONDS)) {
throw new AssertionError("Timed out waiting for " + description);
}
Thread.sleep(15);
}
}
/**
* Loads managed FXML with application-supplied dependencies on the FX thread.
* @param fxml view resource
* @param model model for the view
* @param dependencies adapter for View objects and services
* @return managed view
* @throws Exception if the view cannot be loaded or the wait is interrupted or times out
*/
public LoadedView loadWithDependencies(URL fxml, Object model, ViewDependencies dependencies) throws Exception {
return call(() -> ViewLoader.loadWithDependencies(fxml, model, dependencies, models));
}
void finish() throws Exception {
run(() -> {
try {
for (var window : List.copyOf(Window.getWindows()).reversed()) {
if (!previousWindows.contains(window)) window.hide();
}
} finally {
try {
models.close();
} finally {
Thread.currentThread().setUncaughtExceptionHandler(previousHandler);
}
}
if (!callbackFailures.isEmpty()) {
var failure = new AssertionError("Unhandled exception on the JavaFX application thread",
callbackFailures.getFirst());
callbackFailures.stream().skip(1).forEach(failure::addSuppressed);
throw failure;
}
});
}
}
@@ -0,0 +1,20 @@
package de.neitzel.fx.test;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.junit.jupiter.api.parallel.Isolated;
/** Runs a JavaFX test class in isolation and supplies an FxFixture to each test method. */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Isolated
@Execution(ExecutionMode.SAME_THREAD)
@ExtendWith(FxExtension.class)
public @interface FxTest {}
@@ -0,0 +1,65 @@
package de.neitzel.fx.test;
import de.neitzel.fx.view.ViewDependencies;
import de.neitzel.fx.view.ViewObject;
import java.util.Optional;
import java.io.IOException;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import lombok.Getter;
import lombok.Setter;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
@FxTest
public class FxFixtureTest {
@Getter @Setter
public static class Person {
private String name = "Ada";
}
@Test
void teardownDetachesLoadedViewsAndReportsUnhandledCallbacks(FxFixture fx) throws Exception {
var person = new Person();
var nested = new FxFixture();
var problem = new IllegalStateException("callback failed");
nested.start();
var view = nested.loadWithDependencies(getClass().getResource("name.fxml"), person, new ViewDependencies() {
public boolean isComponent(Class<?> type) { return false; }
public <T> Optional<T> findService(Class<T> type) { return Optional.empty(); }
public <T> ViewObject<T> createViewObject(Class<T> type) {
throw new AssertionError("Unexpected view type: " + type);
}
});
var field = nested.call(() -> (TextField) view.getRoot());
var stage = nested.call(() -> {
assertEquals("Ada", field.getText());
field.setText("Lin");
assertEquals("Lin", person.getName());
var window = new Stage();
window.setScene(new Scene(field));
window.show();
return window;
});
nested.run(() -> Platform.runLater(() -> { throw problem; }));
assertSame(problem, assertThrows(AssertionError.class, nested::finish).getCause());
fx.run(() -> {
assertFalse(stage.isShowing());
field.setText("Detached");
assertEquals("Lin", person.getName());
});
}
@Test
void nestedCallsPropagateTheOriginalFailureAndCannotBlockTheFxThread(FxFixture fx) throws Exception {
var problem = new IOException("failed");
assertSame(problem, assertThrows(IOException.class, () -> fx.run(() -> {
assertTrue(fx.call(Platform::isFxApplicationThread));
assertThrows(IllegalStateException.class, () -> fx.await("next pulse", () -> false));
throw problem;
})));
}
}
@@ -0,0 +1,8 @@
<?import de.neitzel.fx.view.BindingList?>
<?import de.neitzel.fx.view.DirectBinding?>
<?import javafx.scene.control.TextField?>
<TextField xmlns:fx="http://javafx.com/fxml/1" fx:id="field">
<fx:define><BindingList>
<DirectBinding control="field" property="text" path="name" direction="both"/>
</BindingList></fx:define>
</TextField>
+94 -43
View File
@@ -35,7 +35,7 @@
`fx` includes docking and standalone bars for ordinary JavaFX applications; these controls do not require MVVM initialization. Its optional MVVM functionality binds an FXML view to an ordinary Java model. The model stays a JavaBean. The library builds one view model for that instance, loads the view, and applies the binding elements declared in the FXML.
You write the model, the FXML, and, where a screen needs them, a controller, reusable components, and converters. The library creates the view model. The [injection](../injection/README.md) container creates the controller, each component, and each converter.
You write the model, the FXML, and, where a screen needs them, a controller, reusable components, and converters. The library creates the view model. The application's `ViewDependencies` supplies controllers, components and converters.
The worked example is the `fx-example` module, package `de.neitzel.fx.example`. From the NeitzelLib root, with Java 25:
@@ -46,7 +46,11 @@ The worked example is the `fx-example` module, package `de.neitzel.fx.example`.
The launch class is `de.neitzel.fx.example.Main`. `Main` does not extend `Application`. It calls `Application.launch(DeskApp.class, args)`, and `DeskApp.start` builds the scene on the JavaFX thread.
Depend on `de.neitzel.lib:fx`. That module depends on `core`, `injection` and on JavaFX base, controls, graphics, fxml, and web. Application types the container constructs use `jakarta.inject.Singleton` or `jakarta.inject.Named`.
Depend on `de.neitzel.lib:fx` for your own adapter. For Neitzel's
`ApplicationContext`, depend on [`de.neitzel.lib:fx-injection`](../fx-injection/README.md).
That artifact brings in `fx` and `injection`.
Use `ViewLoader.loadComponentWithDependencies(type, model, dependencies, models)` to open a reusable Component directly from its own FXML. It returns a managed `LoadedView` with the same Component, ViewModel selection and binding lifetime as an embedded instance.
## Dependencies
@@ -56,27 +60,26 @@ These are the versions configured by this source snapshot, not a promise of comp
| --- | --- | --- |
| JDK | Java 25 | Select a matching JDK for compilation and launch |
| Maven | Minimum 3.9.11; wrapper 3.9.11 | Use the wrapper or an installed Maven |
| Library | `de.neitzel.lib:fx:1.0.5` | Use the Gitea Maven registry or install the local reactor |
| Internal modules | `fx` directly depends on `core`, `injection` and toolkit-independent `data-grid` | Resolved transitively through Maven |
| Library | `de.neitzel.lib:fx:1.0.7` | See [Maven setup](../README.md#use-a-release-from-maven). |
| Internal modules | `fx` directly depends on `core` and toolkit-independent `data-grid` | Resolved transitively through Maven |
| JavaFX | 27.0.1: base, graphics, controls, FXML and web | Resolved transitively; deployment still needs platform-native artifacts |
| Saved HTML | jsoup 1.23.2, ph-css 8.2.3, TwelveMonkeys WebP 3.15.3 | Resolved transitively by `fx`; no separate application setup |
| Injection scanning | Reflections 0.10.2 | Brought by `injection` |
| Injection annotations | `jakarta.inject-api` 2.0.1 | Use Jakarta annotations, not `javax.inject` |
| Optional Neitzel DI | `fx-injection` → `injection`, Reflections and Jakarta Inject | Include when you choose Neitzel's container |
| Logging | SLF4J API 2.0.20 | Choose one logging backend; the example uses `slf4j-simple` 2.0.20 at runtime |
| Library build | Lombok 1.18.48 and test/analysis tooling | Not required in ordinary consumer source; use your own annotations only if wanted |
| Designer | Optional preview API / Model processor | Needed only for the selected Designer workflow, not normal `ViewLoader` use |
The quick-start POM adds only `fx` and a logging backend. Do not copy library build-time dependencies into an application just to obtain runtime binding. A project using injection alone needs the `injection` artifact and does not need JavaFX.
The published 1.0.6 quick start uses its matching POM and APIs. Do not copy library build-time dependencies into an application just to obtain runtime binding. A project using injection alone needs the `injection` artifact and does not need JavaFX.
## Quick start
`DeskApp` scans its package, loads one person into `Desk.fxml`, and asks for a dialog when a new message is added:
```java
ApplicationContext context = new ApplicationContext(DeskApp.class);
Person person = DeskApp.sample();
LoadedView loaded = ViewLoader.load(
DeskController.class.getResource("Desk.fxml"), person, context);
ViewModelContext models = new ViewModelContext();
LoadedView loaded = ViewLoader.loadWithDependencies(
DeskController.class.getResource("Desk.fxml"), person, DeskApp.dependencies(person), models);
MessagePopup.showNewMessages(loaded.getViewModel());
Parent root = loaded.getRoot();
```
@@ -92,9 +95,9 @@ Parent root = loaded.getRoot();
<TextField fx:id="nameField"/>
```
`ApplicationContext` scans the package of the class you pass, and its subpackages. `DeskApp` carries `@Config(basePackage = "de.neitzel.fx.example")`, which is that package. `ViewLoader.load` reuses the view model already built for that person, or builds one, then loads the FXML and applies the binding elements.
`ApplicationContext` scans the package of the class you pass, and its subpackages. `DeskApp` carries `@Config(basePackage = "de.neitzel.fx.example")`, which is that package. `ViewLoader.loadWithDependencies` reuses the view model already built in its Model context for that person, or builds one, then loads the FXML and applies the binding elements.
One model instance has one view model. The first view fixes the view model class. The desk's controller names `PersonViewModel`, so that is the class for this person.
One Model instance has one ViewModel per Model context. The first view fixes the view model class. The desk's controller names `PersonViewModel`, so that is the class for this person.
## The person desk
@@ -148,7 +151,8 @@ After the view model exists, it is the writer. A property change calls the sette
## Load a view
```java
public static LoadedView load(URL fxml, Object model, ApplicationContext context)
public static LoadedView loadWithDependencies(URL fxml, Object model,
ViewDependencies dependencies, ViewModelContext models)
```
The load reads `fx:controller` from the document first, so it can see `@ViewModelClass`, and builds or reuses the view model. It then loads the FXML. The container supplies the controller. Components come from the container as well. The root must be a `Parent`. Bindings run after `@FXML` fields are filled. Tables under the root open last, including a table inside a scroll pane.
@@ -157,9 +161,50 @@ The load reads `fx:controller` from the document first, so it can see `@ViewMode
`LoadedView.property(String)` returns the JavaFX property for an attribute name, for `latestMessage`, or for a `nameProperty()` method on the view model. A missing name returns null. A binding whose path does not resolve fails the load.
FXML that cannot be read becomes `IllegalStateException` `Could not load view` and the URL. A missing controller class is `IllegalArgumentException` `No controller` and the name.
FXML that cannot be read becomes `IllegalStateException` `Could not load view` and the URL. A missing controller class is reported with `No controller` and the name in the cause.
`DeskLoadsTest.secondViewReusesTheViewModel` loads a second document, `NameLine.fxml`, for the same person. The second document names no controller and no view model class. It reuses `PersonViewModel`. Typing in the desk's name field updates the second field, and the title becomes `titled-Grace`. Loading `Desk.fxml` a second time while the first desk is showing does not work: the home `AddressForm` is the cached singleton and already has children. See [Component](#component).
`DeskLoadsTest.secondViewReusesTheViewModel` loads a second document, `NameLine.fxml`, for the same person. The second document names no controller and no view model class. It reuses `PersonViewModel`. Typing in the desk's name field updates the second field, and the title becomes `titled-Grace`.
### Use an application DI container
Use `ViewDependencies` with the managed loader when your application owns a
DI container. Construct the adapter once for that container. Open views on
the JavaFX application thread and keep their `ViewModelContext` for their
lifetime.
```java
ViewModelContext models = new ViewModelContext();
LoadedView view = ViewLoader.loadWithDependencies(fxml, model, dependencies, models);
stage.setScene(new Scene(view.getRoot()));
stage.addEventHandler(WindowEvent.WINDOW_HIDDEN, event -> models.close());
```
Use `ViewLoader.loadComponentWithDependencies(ComponentType.class, model,
dependencies, models)` for a Component's own `fx:root` document.
`FxFixture.loadWithDependencies(fxml, model, dependencies)` loads the
same way on the test's JavaFX thread and owns its model context.
Implement the three methods of `ViewDependencies`.
- `isComponent(type)` checks an exact Component registration before FXML
creates the object. A set of the Component classes with their own FXML is
sufficient. Return false for ordinary JavaFX elements.
- `createViewObject(type)` supplies a fresh injected Controller or Component
and a release action in a `ViewObject`. Use concrete FXML types and an
unshared scope for UI classes. Register services such as storage separately
with the scope they need. In Spring, a named prototype bean and
`destroyBean(name, instance)` are one way to implement this method.
- `findService(type)` resolves application-owned Converters and the optional
`Localizer`. Return `Optional.empty()` for an absent binding. Propagate
lookup and creation failures so the load can report the right cause.
DI construction precedes `@FXML` injection. Use JavaFX `initialize()`
for access to FXML fields and the ViewModel handoff for work that needs that
ViewModel. When a view is closed, a dynamic child is removed or a load rolls
back, FX detaches its bindings and calls the associated release action.
Close your container after its views. To update a caller that used the
published `ApplicationContext` overloads, follow the
[Neitzel adapter migration](../fx-injection/README.md#migrate-an-existing-fx-application).
## Direct binding
@@ -173,7 +218,7 @@ For `both` and `model`, the write happens when the JavaFX property changes, incl
`BindingList` is the element that holds direct bindings, computed bindings, command bindings, and repeats. Its default property is `elements`, so the children in FXML are the list. An unknown child fails the load with `Not a binding element:`. Command bindings require a managed View.
When the attribute value is already an `ObservableList`, the control property is set to that same list. Direction and converter are not consulted. The tag binding names `direction="view"` and still shares the list. See [A list of simple values](#a-list-of-simple-values).
When the attribute value is already an `ObservableList`, the control property is set to that same list. With `direction="view"`, the control also follows replacement of the list reference, including a replacement with equal elements. Closing a managed View detaches that observation and restores the previous list if the control still holds the supplied list. Other directions retain their shared-list assignment. The writable observable-list path bypasses converters. See [A list of simple values](#a-list-of-simple-values).
A binding that names no such control fails with `No control "` and the id. A missing `xxxProperty()` method fails with `No property` and the property name. A method that returns something other than a `Property` fails with `did not return a property`.
@@ -355,13 +400,15 @@ try (var saving = new AsyncCommand<Void>(valid, executor, createSaveTask)) {
## Controller
Name the class on the root with `fx:controller`. The container creates it with `getComponent`, so it is the cached singleton. `@FXML` fields are filled during load, before the bindings run.
Name the class on the root with `fx:controller`. The adapter creates a fresh instance for the View. `@FXML` fields are filled during load, before the bindings run.
Leave `fx:controller` off and the library supplies a controller, which is enough for a view that has only direct bindings. `NameLine.fxml` in the test is that shape. You cannot obtain the supplied controller from `LoadedView`.
Implement `HasViewModel` when your code needs the view model. The library calls `setViewModel` after construction and before the bindings run, and only when the selected object is a `ViewModel`. The desk stores it and reads `visits`, `tags`, `name`, and `age` from it.
A second view whose document names the same controller class receives that same singleton. FXML then injects the second view's fields into it. The desk is one window, so its controller fields stay on that window. Give a second screen its own controller class when each screen needs its own `@FXML` fields.
Each load receives its own controller and `@FXML` fields. Share
application state through a service. The desk shares `VisitActions` with
its table rows.
## Choosing the ViewModel class
@@ -411,7 +458,7 @@ remain handled by the containing FXMLLoader.
A component is a class the container can create. It extends `Parent` (usually a Pane subclass such as `VBox`), loads `ClassName.fxml` from its own package through `fx:root`, and is the controller of that file. It has no `fx:controller`. It exposes one JavaFX property named `model`.
`AddressForm` edits the home address. `VisitForm` edits one visit in the repeated list. `NoteForm` edits a note. `VisitRow` edits one table row. Each is `@Singleton`, extends `VBox` or `HBox`, and has `modelProperty()`.
`AddressForm` edits the home address. `VisitForm` edits one visit in the repeated list. `NoteForm` edits a note. `VisitRow` edits one table row. Each extends `VBox` or `HBox` and has `modelProperty()`. In the example, `@Singleton` marks the classes for Neitzel's scanner. The adapter creates a fresh instance for each occurrence.
The home document binds the form and sets `model` from the path. When the path's last segment is complex, the value assigned is the model instance behind that view model.
@@ -424,9 +471,9 @@ The component's own bindings run once, the first time `model` becomes non-null.
`initialize` runs during the component's FXML load, before `model` is set. `AddressForm` uses that moment to copy the injected heading onto its label, which does not need the address. For a Component implementing `HasViewModel`, `setViewModel` runs after `model` is set to a non-null Model and before its bindings, but only when the selected presentation object extends `ViewModel`. An arbitrary replacement does not receive this callback. `AddressForm` implements `HasViewModel` and writes `Opened as ` plus the city at that moment. Editing the city afterward leaves the label on the city the form opened with. The sample home opens as `Opened as Sample City`.
The first component of a class in one load is `context.getComponent`, the cached singleton. Each further one in that same load is `context.createComponent`. Repeat and table rows always use `createComponent`, so they are new instances and the cached singleton of that class stays unused by the rows. `getComponent(VisitForm.class)` after the desk loads is still the singleton, and the three forms in the visit pane are other instances.
A later load starts over. Its first component of a class is the cached singleton again. The home `AddressForm` is that singleton and is already in the scene, so loading `Desk.fxml` a second time fails while building the home form: a node cannot be added to a second parent. The test's second view is a document with no component.
Every registered FXML Component is created fresh, including Repeat children
and table rows. The Neitzel adapter uses `createComponent` and leaves the
context's shared registrations available to other callers.
A component class needs `ClassName.fxml` beside it. A missing document fails with `No component document`. A missing `modelProperty` method fails with `No model property on`. A method that does not return a `Property` fails with `modelProperty did not return a property`.
@@ -436,7 +483,8 @@ A nested component is the same mechanism one level down. The child document name
`AddressForm.fxml` binds `noteForm` to path `note` and contains `<NoteForm fx:id="noteForm"/>`. `NoteForm.fxml` binds its text field to path `text`. The sample home note is `Kept at home`. Editing the note field writes `text` on the existing `Note` held by `Address.note`; it does not replace that Note object.
`VisitForm` does not contain `NoteForm`. A visit added after the desk has loaded is built in a new load. The first component of a class in that load is the cached singleton again, so a `NoteForm` nested in the repeated form would be the instance already showing under the home address. Keeping the note on the home form, which is loaded once, leaves that singleton where it was placed.
`VisitForm` displays the visit fields. The desk shows a note editor in
the home address form.
A null `note` leaves the nested binding unapplied. `NoteForm` stays empty and the load succeeds. The sample home has a note, so its bindings run.
@@ -521,7 +569,7 @@ Add and remove update the body. A permutation or an extractor update notificatio
A column attribute must be a simple value: string, boolean, enum, a primitive other than `char` and `void`, a `Number`, a `Date`, a `Calendar`, or a `java.time` temporal. `visitedOn` is a `LocalDate`, so it is a column. A complex attribute fails the load with `Attribute "` name `" is not a simple value`.
Other load failures, all `IllegalArgumentException`:
Other load failures reported in the cause:
| Condition | Message |
| --- | --- |
@@ -541,7 +589,7 @@ Use the four-argument loader when a window, dialog or dockable owns a View:
```java
try (var models = new ViewModelContext();
var loaded = ViewLoader.load(fxml, model, application, models)) {
var loaded = ViewLoader.loadWithDependencies(fxml, model, dependencies, models)) {
// Use loaded.getRoot() while this View is open.
}
```
@@ -552,14 +600,10 @@ those on components and collection rows. Close its `ViewModelContext` once the o
window or archive ends. The context closes remaining Views and releases the Model-to-ViewModel
registrations. Views of the same model instance in one context share a ViewModel.
The managed loader creates a fresh injected Controller or Component for each instance.
Dependencies still come from the application context. Controllers and Components can
implement `AutoCloseable` to release additional resources such as programmatic event handlers
or subscriptions to application services. The library also closes these resources if FXML or
binding setup throws. Use these handles on the FX application thread.
The three-argument loader keeps its existing shared cache and Controller behavior. Manage a
View with the four-argument loader if it needs deterministic cleanup.
The adapter supplies a fresh Controller or Component and its release action. FX invokes
that action on close and when it rolls back an unsuccessful load. The Neitzel adapter
calls `AutoCloseable.close()` for UI instances that implement it. Use these handles
on the FX application thread.
### Column width
@@ -647,21 +691,21 @@ A list element is not a nested view model. A failure recorded on a visit is carr
## What the container creates
`ViewLoader.load` takes an `ApplicationContext`. The view model is never created by the container.
`ViewDependencies` provides the following objects. The Model context
creates or reuses the ViewModel.
| Object | How it is created |
| Object | How it is resolved |
| --- | --- |
| Controller named by `fx:controller` | `getComponent`, once |
| Converter named on a direct binding | `getComponent` |
| First component of a class in a load | `getComponent`, when that instance is free to place |
| Another element of that class in the same load | `createComponent` |
| Repeat children and table rows | `createComponent` |
| Controller named by `fx:controller` | A fresh `ViewObject` from `createViewObject` |
| Converter named on a direct binding | `findService` on the declared class |
| Embedded and standalone Components, Repeat children and table rows | Exact registration and a fresh `ViewObject` per instance |
| Optional `Localizer` | `findService(Localizer.class)` |
Details of scanning, `@Singleton`, `@Named`, constructor, field, and setter injection, and `@Config` are in the [injection guide](../injection/README.md). The desk's scan root is `DeskApp`.
## When a load fails
These are the `IllegalArgumentException` messages a document can produce. The view is not shown.
The loader reports the FXML resource and preserves the exception with the specific cause.
| Message | Cause |
| --- | --- |
@@ -696,7 +740,9 @@ The reference above covers the FXML declarations and their behavior. These are t
| Responsibility | Types and key members |
| --- | --- |
| Load | `ViewLoader.load`, `LoadedView.getRoot`, `getViewModel`, `property` |
| Load | `ViewLoader.loadWithDependencies`, `loadComponentWithDependencies`, `LoadedView.getRoot`, `getViewModel`, `property` |
| Lifetime | `ViewModelContext`, `LoadedView.close()` |
| Dependency integration | `ViewDependencies`, `ViewObject` |
| Presentation state | `ViewModel.property`, protected `storedProperty`, `HasViewModel.setViewModel`, `@ViewModelClass` |
| Declarations | `BindingList`, `DirectBinding`, `ComputedBinding`, `Repeat`; JavaBean setters correspond to the FXML attributes described above |
| Convert values | `Converter.toControlValue`, `toAttributeValue` |
@@ -707,4 +753,9 @@ The reference above covers the FXML declarations and their behavior. These are t
`property(name)` returns `Property<?>`: cast to the known property type when writing from Java, for example `((StringProperty) loaded.property("name")).set("Grace")`. Generated accessors avoid these casts. `storedProperty` is for subclasses and reads only stored Model Attributes; it does not invoke custom reflective accessors. Internal loaders, appliers and identity-cache helpers are implementation details, not extension APIs.
For threading, strong identity retention, context reuse, the absence of a general disposal API, and JPMS reflection, see [architecture and lifetime](docs/architecture.md). For an independent application POM and runnable files, use the [complete quick start](docs/quick-start.md).
For threading, Model identity, resource release and reflective module access, see [architecture and lifetime](docs/architecture.md). For an independent application POM and runnable files using the 1.0.6 release, use the [complete quick start](docs/quick-start.md).
DataGrid columns accept arbitrary string keys for group captions through the attached
`DataGridColumn.groupLabel` property. For example,
`<DataGridColumn.groupLabel><javafx.util.Pair key="Post/Eingang West" value="Eingang"/></DataGridColumn.groupLabel>`
writes the literal key into the same map as `<groupLabels Post="Postfach"/>`.
+23 -19
View File
@@ -8,14 +8,14 @@ NeitzelLib creates that presentation layer at runtime. You can subclass it for a
```mermaid
flowchart TD
App[Application: Model + ApplicationContext] --> Loader[ViewLoader]
App[Application: Model + ViewDependencies] --> Loader[ViewLoader]
FXML[FXML: controls and binding declarations] --> Loader
Loader --> View[LoadedView: JavaFX root]
Loader --> VM[Runtime ViewModel]
Model[JavaBean Model] -->|Initial getter read / lazy child resolution| VM
VM -->|Property change calls setter| Model
View <-->|DirectBinding| VM
Context[ApplicationContext] --> Controller[Controller / Computed methods]
Context[ViewDependencies] --> Controller[Controller / Computed methods]
Context --> Converter[Converters]
Context --> Component[Component root and controller]
Controller --> View
@@ -30,7 +30,7 @@ The [dependency baseline](../README.md#dependencies) distinguishes application r
## Loading order
`ViewLoader.load` reads the controller declaration and its ViewModel selection, obtains or creates the Model's ViewModel, then loads FXML. The injection context supplies controllers, Components and Converters. JavaFX performs normal `@FXML` field injection and calls `initialize`. After loading, the library supplies the ViewModel to `HasViewModel` only when the selected object extends `ViewModel` (replacement objects do not receive this callback), applies BindingLists in document order, and opens custom Tables.
`ViewLoader.loadWithDependencies` reads the controller declaration and its ViewModel selection, obtains or creates the Model's ViewModel, then loads FXML. The adapter supplies controllers, Components and Converters. JavaFX performs normal `@FXML` field injection and calls `initialize`. After loading, the library supplies the ViewModel to `HasViewModel` only when the selected object extends `ViewModel` (replacement objects do not receive this callback), applies BindingLists in document order, and opens custom Tables.
Consequently, `initialize` must not assume that `HasViewModel.setViewModel` has already run. A Component's own bindings wait for its first non-null Model. Binding order can matter when an earlier declaration causes a nested Model's ViewModel to be created before a later Component requests a more specific class.
@@ -40,7 +40,11 @@ Consequently, `initialize` must not assume that `HasViewModel.setViewModel` has
Attributes are JavaBeans properties with both a getter and setter. Runtime properties are initialized from the bean and changes to them call its setter. Direct calls to a bean setter do not send notifications back to the runtime property. Update the ViewModel on the JavaFX application thread when application logic should update an existing View.
The runtime holds a **global, strong, identity-based cache** of Model-to-ViewModel associations. The same Model object shares one ViewModel across Views and contexts; equal but distinct beans do not. Registration before traversing children supports cyclic graphs. There is no public eviction or release API. Treat this as an explicit limitation for applications with many short-lived Models.
Each managed `ViewModelContext` stores Model-to-ViewModel associations
by object identity. Views in the same context can share the ViewModel
for the same Model object. Independent contexts have independent
registrations. Registration before traversing children supports cyclic graphs.
Closing the context releases its registrations and closes the remaining Views.
Complex Attributes are mapped lazily to nested ViewModels. A null child stays null. A dotted binding resolves intermediate objects when the binding is applied; it does not dynamically reattach after replacing an intermediate child. Bind a Component's `model` to the complex Attribute when you want a subform, but note that the current Component implementation also applies its internal bindings only for its first non-null Model.
@@ -48,24 +52,24 @@ Lists are shared ObservableLists when possible. A `List` bean setter generally a
## Context and View lifetime
The [injection context](../../injection/README.md) caches one instance of every scanned class. This includes controllers and converters. Reusing a controller in multiple live Views overwrites its injected FXML fields. Components reuse the context instance for the first occurrence of a class in a load and create fresh instances for additional occurrences; Repeat and Table explicitly create fresh row roots. Nested Components still need care when the same context is reused across independent loads.
Use one adapter for a container and give each logical window or document
a Model context. Related Views can share a Model context. Each View
receives fresh Controller and Component instances. Share services through
the adapter.
Use a separate context for independent windows unless shared controller/component lifetime is intentional. This does not isolate the global Model identity cache: use separate Model instances if you need independent drafts.
There is no general `LoadedView.close()`, ViewModel disposal, unbind-all operation, or container shutdown hook. Bindings, collection listeners and MessagePopup listeners can retain objects. Closing a Stage does not constitute a documented cleanup contract for these listeners. Install popup listeners once, keep application lifetimes bounded, and test long-running/repeated-window workloads before depending on this snapshot.
Close a `LoadedView` when it leaves the application. Its bindings and
listeners are detached, and the adapter's release actions run for its
Controller and child Components. Close the Model context when its owner
ends. Close the application-owned container after its Views. The optional
[Neitzel adapter](../../fx-injection/README.md) uses the existing
ApplicationContext lookup for shared services and fresh instances for the UI.
Run loading, scene changes, observable property updates and message operations on the JavaFX application thread. The context and ViewModel cache are not concurrent services. Perform slow I/O separately and deliver results with `Platform.runLater`; do not perform it inside Computed methods or property listeners.
## Modules and reflection
The library artifacts currently act as automatic modules named `fx` and `injection`. An application using JPMS generally needs `requires fx`, `requires injection`, `requires jakarta.inject`, `requires javafx.controls` and `requires javafx.fxml`. The precise requirements depend on its imports.
Open bean packages to `fx` for reflective Attribute access. FXML controller and Component packages need reflective access for JavaFX and the library/container; an unqualified `opens your.controls;` is a straightforward starting point while diagnosing a modular application. Injection may invoke non-public constructors and members. Generated ViewModel packages also require suitable exports/opens, and a named-module registry uses `provides de.neitzel.fx.view.ViewModelRegistry with ...` rather than only a classpath service file.
Package scanning depends on the runtime's class/module paths. Verify the real modular launch; success on the classpath does not prove a module configuration is correct. The Designer separately validates classpath and module-path target applications and keeps its Kit runtime distinct from the application's JavaFX runtime.
## Choosing extensions
Start with generic runtime properties. Add a ViewModel subclass for derived presentation state and a controller for event handling. Use [generated ViewModels](generated-viewmodels.md) for typed access and shared discovery metadata. Use [Components, Repeat and Table](../README.md#component) to reuse form structure. The Designer is an optional authoring tool: the application remains runnable without it.
The library is a development snapshot and a personal helper collection. In particular, it is not a transactional form engine, a virtualized table, a dependency-tracking expression language, or a full dependency injection framework. Keep business validation and persistence boundaries explicit in application code.
A named application using FX typically declares `requires fx`,
`requires javafx.controls` and `requires javafx.fxml`. An application
using the optional Neitzel adapter adds `requires de.neitzel.fx.injection`
and declares `requires injection` and `requires jakarta.inject` where
it uses those types. Each container's own requirements apply to its adapter.
+13 -3
View File
@@ -9,8 +9,8 @@ context. The optional `ViewLoader` applies NeitzelLib binding declarations.
| `de.neitzel.fx.view.DataGrid` | Columns, typed attributes, widths, filters, grouping, page size, `selectionMode` and setup identity | Bind `items` or `source`; explicitly load after configuration, close with the view |
| `de.neitzel.fx.view.Table` | `collection`, `row`, `Column` declarations | Existing ViewLoader collection/Component rows and `selection` binding |
| `de.neitzel.fx.control.StatusBar` | `leftItems`, `rightItems` containing ordinary Nodes | Bind the properties of the contained controls |
| `de.neitzel.fx.control.AutoCompleteTextField` | Standard TextField attributes and a `suggestions` list of strings | Type a prefix, use arrow keys and Enter or select with the mouse. Selecting emits the normal text-field action |
| `de.neitzel.fx.control.HtmlViewer` | `mediaButtonVisible`, `mediaLoadText`, `mediaReloadText`, `mediaTooltipText`, `noExternalMediaText` | Explicit `load` / `loadHtml` / `display`; call `close()` when disposed. See [HTML viewer](html-viewer.md) |
| `de.neitzel.fx.control.AutoCompleteTextField` | Standard TextField attributes, fixed `suggestions` and a bindable `suggestionsSource` of type `ObservableList<String>` | Type a prefix, use arrow keys and Enter or select with the mouse. Selecting emits the normal text-field action |
| `de.neitzel.fx.control.HtmlViewer` | `mediaButtonVisible`, `mediaLoadText`, `mediaReloadText`, `mediaTooltipText`, `noExternalMediaText` | Bind local text to `html` or use `load` / `loadHtml` / `display`; call `close()` when disposed. See [HTML viewer](html-viewer.md) |
| `de.neitzel.fx.control.TagChip` | `text`, `removable` (false by default), `onRemove` | The action handler owns removing the tag from its model |
| `de.neitzel.fx.docking.DockPane` | `initialLayout`, `DockLayout`, group/split definitions | Attach a DockingManager to open application-owned content |
| `de.neitzel.fx.control.NonNegativeIntegerSpinner` | `minimum`, `maximum`, `initialValue` constructor attributes | Bind writable `number`, which shares the value factory's property |
@@ -48,7 +48,7 @@ objects, rather than controls to insert in a scene graph.
```
Initialize the model's `List<Person> people` before loading. Bean and Java record
rows are supported. After `ViewLoader.load`, call the injected grid's `load()` or
rows are supported. After loading with `ViewLoader.loadWithDependencies`, call the grid's `load()` or
`loadAsync()` on the FX thread. The data binding shares the model's observable
list. Add, remove, replace, permute or use an extractor update on that list to
request a refresh immediately, invalidating older pending results. The existing
@@ -114,3 +114,13 @@ The original `IntegerSpinners.nonNegative(...)` factory remains available.
See [bars](bars.md), [docking](docking.md) and the main [FXML reference](../README.md)
for the existing controls. The host designer needs the updated library on its
classpath; this feature does not replace a separately pinned Designer runtime.
### Model-driven suggestions
Use `<DirectBinding control="dynamic" property="suggestionsSource" path="tags" direction="view"/>`
for an observable list of strings. A non-null source (including an empty list) takes precedence over
the fixed FXML entries in `getSuggestions()`. The popup follows replacements and edits to the active
list while the field is attached. Choosing a match sets the field text and fires its action.
Setting the source to null or unbinding `suggestionsSourceProperty()` restores the fixed entries.
Closing a managed DirectBinding restores its previous list source. Removing the field from its
scene dismisses the popup and detaches its list listener.
+12
View File
@@ -34,6 +34,18 @@ message are included. New loads cancel pending work and discard stale results.
`clear()` releases the current content and leaves the viewer reusable. `close()`
also cancels pending work, is idempotent, and makes future loads fail.
## Model-driven source
Bind a string toward the viewer with a DirectBinding such as
`<DirectBinding control="article" property="html" path="html" direction="view"/>`.
For plain JavaFX use `viewer.htmlProperty().bind(source)`. Each changed string uses
the offline `loadHtml` preparation. A null or blank value clears the document.
Rapid changes cancel older preparations and revoke earlier media grants.
The property contains the supplied source. Displaying a prepared document, loading a file,
granting image access or clearing the viewer changes the display without writing to the model.
The next change to the bound text takes effect. Unbinding leaves the current display in place.
Close the viewer on disposal to detach a JavaFX binding and cancel outstanding work.
## External images
Each displayed document starts offline. The included **Load external media**
+1 -1
View File
@@ -1,6 +1,6 @@
# Message catalogs for Java and FXML
Create one Localizer per application. The initial locale can be null to use the JVM display locale. The second argument specifies the fallback language. Register the service with the same ApplicationContext used by ViewLoader.
Create one Localizer per application. The initial locale can be null to use the JVM display locale. The second argument specifies the fallback language. Expose the service through `ViewDependencies.findService(Localizer.class)`. With the Neitzel adapter, register it in the underlying `ApplicationContext`.
```java
var language = new Localizer(initialLocale, Locale.ENGLISH,
+15 -5
View File
@@ -1,13 +1,17 @@
# Your first JavaFX application
This walkthrough creates a complete Maven project with one editable name and a label that follows it. It uses Java 25, JavaFX 27.0.1 and NeitzelLib 1.0.5. The source build below uses the matching release tag.
This walkthrough creates a complete Maven project with one editable name and a label that follows it. It uses Java 25, JavaFX 27.0.1 and NeitzelLib 1.0.6. The source build below uses the matching release tag.
For the separated FX runtime introduced in 1.0.7 and its managed loader, see
[FX loading](../README.md#load-a-view) and the
[optional Neitzel adapter](../../fx-injection/README.md).
## Prepare the library
Install a JDK 25. Use the library's Maven wrapper (3.9.11), or a separate Maven installation version 3.9.11 or newer. Check `java -version` and `./mvnw -version` before building; on macOS, select the JDK with `export JAVA_HOME=$(/usr/libexec/java_home -v 25)` if necessary.
```bash
git clone --branch v1.0.5 https://gitea.neitzel.de/konrad/NeitzelLib.git
git clone --branch v1.0.6 https://gitea.neitzel.de/konrad/NeitzelLib.git
cd NeitzelLib
./mvnw -pl fx-example -am install
./mvnw -f fx-example/pom.xml javafx:run
@@ -33,7 +37,7 @@ print(f'{len(reports)} test suites passed')
PYTHON
```
Use a clean build when qualifying a change so stale reports cannot stand in for tests that did not run.
Use a clean build when qualifying a change so stale reports cannot stand in for tests that did not run. The standalone POM below can also resolve the published 1.0.6 artifacts directly.
## Create the application
@@ -62,11 +66,17 @@ hello-fx/
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>gitea-neitzellib</id>
<url>https://gitea.neitzel.de/api/packages/konrad/maven</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>fx</artifactId>
<version>1.0.5</version>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
@@ -190,7 +200,7 @@ For a named-module application, see the [module and lifecycle notes](architectur
| Symptom | Check |
| --- | --- |
| Maven cannot resolve `de.neitzel.lib:fx:1.0.5` or its parent | Install the library reactor first; use the same Maven local repository for both projects. For direct downloads, see the [Maven repository setup](../../README.md#use-a-release-from-maven). |
| Maven cannot resolve `de.neitzel.lib:fx:1.0.6` or its parent | Install the library reactor first; use the same Maven local repository for both projects. For direct downloads, see the [Maven repository setup](../../README.md#use-a-release-from-maven). |
| `No plugin found for prefix 'javafx'` | Invoke the example POM directly, or use the complete application POM above. Do not invoke the goal on the library reactor parent. |
| JavaFX runtime/native library failure | Check the JDK version, architecture and JavaFX dependencies actually resolved; avoid mixing native artifacts from different platforms or JavaFX versions. |
| `getResource(...)` returns null | The FXML belongs under `src/main/resources` in the matching package; verify it was copied to `target/classes`. Resource names are case-sensitive. |
+9 -9
View File
@@ -7,7 +7,7 @@
<parent>
<groupId>de.neitzel.lib</groupId>
<artifactId>neitzellib</artifactId>
<version>1.0.5</version>
<version>1.0.8-SNAPSHOT</version>
</parent>
<artifactId>fx</artifactId>
@@ -18,6 +18,11 @@
<launcher>${project.artifactId}</launcher>
<appName>${project.artifactId}</appName>
<jar.filename>${project.artifactId}-${project.version}</jar.filename>
<!-- Dependency versions -->
<imageio-webp.version>3.15.3</imageio-webp.version>
<jsoup.version>1.23.2</jsoup.version>
<ph-css.version>8.2.3</ph-css.version>
</properties>
<dependencies>
@@ -47,17 +52,17 @@
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.23.2</version>
<version>${jsoup.version}</version>
</dependency>
<dependency>
<groupId>com.helger</groupId>
<artifactId>ph-css</artifactId>
<version>8.2.3</version>
<version>${ph-css.version}</version>
</dependency>
<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-webp</artifactId>
<version>3.15.3</version>
<version>${imageio-webp.version}</version>
</dependency>
<!-- NeitzelLib dependencies -->
@@ -67,11 +72,6 @@
<artifactId>core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>de.neitzel.lib</groupId>
<artifactId>injection</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<build>
@@ -1,9 +1,13 @@
package de.neitzel.fx.control;
import java.util.Locale;
import javafx.beans.InvalidationListener;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.collections.WeakListChangeListener;
import javafx.event.ActionEvent;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
@@ -16,6 +20,18 @@ import javafx.stage.Popup;
public final class AutoCompleteTextField extends TextField {
private static final int ROW_HEIGHT = 26;
private final ObservableList<String> suggestions = FXCollections.observableArrayList();
private final ObjectProperty<ObservableList<String>> suggestionsSource =
new SimpleObjectProperty<>(this, "suggestionsSource") {
@Override public void unbind() {
if (isBound()) {
super.unbind();
set(null);
}
}
};
private final ListChangeListener<String> contentChanged = change -> updateSuggestions();
private final WeakListChangeListener<String> weakContentChanged = new WeakListChangeListener<>(contentChanged);
private ObservableList<String> observedSuggestions;
private final ListView<String> choices = new ListView<>();
private final Popup popup = new Popup();
private boolean accepting;
@@ -29,9 +45,12 @@ public final class AutoCompleteTextField extends TextField {
var value = choices.getSelectionModel().getSelectedItem();
if (event.getButton() == MouseButton.PRIMARY && value != null) accept(value);
});
suggestions.addListener((ListChangeListener<String>) change -> updateSuggestions());
suggestionsSource.addListener((InvalidationListener) ignored -> observeSuggestions());
textProperty().addListener((property, before, after) -> updateSuggestions());
sceneProperty().addListener((property, before, after) -> popup.hide());
sceneProperty().addListener((property, before, after) -> {
popup.hide();
observeSuggestions();
});
disabledProperty().addListener((property, before, disabled) -> {
if (disabled) popup.hide();
});
@@ -42,6 +61,21 @@ public final class AutoCompleteTextField extends TextField {
return suggestions;
}
/** Optional live catalogue. Without a source the fixed FXML suggestions are used. */
public ObjectProperty<ObservableList<String>> suggestionsSourceProperty() { return suggestionsSource; }
public ObservableList<String> getSuggestionsSource() { return suggestionsSource.get(); }
public void setSuggestionsSource(ObservableList<String> value) { suggestionsSource.set(value); }
private void observeSuggestions() {
var source = getSuggestionsSource();
var next = getScene() == null ? null : source == null ? suggestions : source;
if (observedSuggestions == next) return;
if (observedSuggestions != null) observedSuggestions.removeListener(weakContentChanged);
observedSuggestions = next;
if (next != null) next.addListener(weakContentChanged);
updateSuggestions();
}
private void handleKey(KeyEvent event) {
var selection = choices.getSelectionModel();
if (event.getCode() == KeyCode.DOWN || event.getCode() == KeyCode.UP && popup.isShowing()) {
@@ -67,11 +101,11 @@ public final class AutoCompleteTextField extends TextField {
}
private void updateSuggestions() {
if (accepting || !isFocused() || isDisabled() || getScene() == null
if (observedSuggestions == null || accepting || !isFocused() || isDisabled() || getScene() == null
|| getScene().getWindow() == null || !getScene().getWindow().isShowing()) return;
String prefix = getText() == null ? "" : getText().strip().toLowerCase(Locale.ROOT);
var matches = prefix.isEmpty() ? java.util.List.<String>of()
: suggestions.stream().filter(value -> value != null && !value.isBlank())
: observedSuggestions.stream().filter(value -> value != null && !value.isBlank())
.filter(value -> value.toLowerCase(Locale.ROOT).startsWith(prefix)).distinct().limit(10).toList();
choices.getItems().setAll(matches);
choices.getSelectionModel().clearSelection();
@@ -34,6 +34,7 @@ public final class HtmlViewer extends BorderPane implements AutoCloseable {
private final StringProperty mediaReloadText = new SimpleStringProperty(this, "mediaReloadText", "Reload external media");
private final StringProperty mediaTooltipText = new SimpleStringProperty(this, "mediaTooltipText", "Loads external images for this viewer only and contacts their servers.");
private final StringProperty noExternalMediaText = new SimpleStringProperty(this, "noExternalMediaText", "No resolvable external image addresses found.");
private final StringProperty html = new SimpleStringProperty(this, "html");
private HtmlDocument document;
private Task<HtmlDocument> pending;
private long generation;
@@ -41,6 +42,11 @@ public final class HtmlViewer extends BorderPane implements AutoCloseable {
public HtmlViewer() {
getStyleClass().add("html-viewer");
html.addListener((observable, before, value) -> {
if (closed) return;
if (value == null || value.isBlank()) clear();
else loadHtml(value);
});
browser.setContextMenuEnabled(false);
browser.getEngine().setJavaScriptEnabled(false);
loading.bind(preparing.or(browser.getEngine().getLoadWorker().runningProperty()));
@@ -153,6 +159,7 @@ public final class HtmlViewer extends BorderPane implements AutoCloseable {
@Override public void close() {
requireFxThread();
if (closed) return;
html.unbind();
clear();
closed = true;
}
@@ -166,6 +173,11 @@ public final class HtmlViewer extends BorderPane implements AutoCloseable {
if (!Platform.isFxApplicationThread()) throw new IllegalStateException("HtmlViewer requires the JavaFX application thread.");
}
/** Local source text. Imperative display operations do not publish values to this input. */
public StringProperty htmlProperty() { return html; }
public String getHtml() { return html.get(); }
public void setHtml(String value) { requireOpen(); html.set(value); }
public ReadOnlyBooleanProperty loadingProperty() { return loading.getReadOnlyProperty(); }
public boolean isLoading() { return loading.get(); }
public ReadOnlyObjectProperty<Throwable> errorProperty() { return error.getReadOnlyProperty(); }
@@ -1,6 +1,5 @@
package de.neitzel.fx.view;
import de.neitzel.injection.ApplicationContext;
import javafx.beans.DefaultProperty;
import javafx.scene.Parent;
import lombok.Getter;
@@ -42,7 +41,7 @@ public class BindingList {
* @param context the container that creates a named Converter
*/
void apply(Map<String, Object> namespace, Object viewModel, Object controller, Parent root,
ApplicationContext context, ViewLifetime lifetime) {
ViewInstances context, ViewLifetime lifetime) {
for (Object element : elements) {
if (element instanceof DirectBinding directBinding) {
DirectBindingApplier.apply(namespace, viewModel, directBinding, context, lifetime);
@@ -48,9 +48,6 @@ final class CommandBindingApplier {
static void apply(Map<String, Object> namespace, Object viewModel, CommandBinding binding,
ViewLifetime lifetime) {
if (!lifetime.managed()) {
throw invalid(namespace, binding, "CommandBinding requires a ViewModelContext");
}
var target = target(namespace, binding);
var command = command(namespace, binding, viewModel);
try {
@@ -1,6 +1,5 @@
package de.neitzel.fx.view;
import de.neitzel.injection.ApplicationContext;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
@@ -37,35 +36,9 @@ final class Components {
private Components() {
}
/**
* Returns a builder for a type the container knows.
* <p>
* An unknown type, such as a JavaFX control, makes {@link ApplicationContext#getComponent}
* throw {@link IllegalArgumentException}. This method returns null so FXML constructs that
* type itself. A Component that extends a JavaFX class is also left to FXML when the document
* names that JavaFX class: the container would otherwise hand back the Component. A failure
* while creating a known Component is not caught. The first Component of a class in one load
* is the cached singleton. A second Component of that class is a new injected instance, so the
* document can show two of them.
*
* @param type the type FXML is about to construct
* @param context the container that creates Components
* @return a builder for a Component, or {@code null} when the type is not a Component
*/
static Builder<?> builder(Class<?> type, ApplicationContext context, ViewLifetime owner) {
Object component;
try {
component = owner.managed() ? context.createComponent(type) : context.getComponent(type);
} catch (IllegalArgumentException notAComponent) {
return null;
}
if (component.getClass() != type) {
return null;
}
if (!owner.managed() && !LoadSession.claimFirst(type)) {
component = context.createComponent(type.asSubclass(Object.class));
}
return new ComponentBuilder(component, context, owner.child());
/** Returns a Component builder or leaves the requested type to JavaFX. */
static Builder<?> builder(Class<?> type, ViewInstances context, ViewLifetime owner) {
return context.isComponent(type) ? new ComponentBuilder(type, context, owner.child()) : null;
}
/**
@@ -74,10 +47,10 @@ final class Components {
*/
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
private static final class ComponentBuilder extends AbstractMap<String, Object> implements Builder<Object> {
/** The injected instance. */
private final Object component;
/** The exact Component class declared by FXML. */
private final Class<?> type;
/** The context used to load its document. */
private final ApplicationContext context;
private final ViewInstances context;
private final ViewLifetime lifetime;
/** Values already resolved by the containing FXMLLoader. */
private final Map<String, Object> values = new LinkedHashMap<>();
@@ -108,7 +81,7 @@ final class Components {
*/
@Override
public Object build() {
Object result = load(component, context, lifetime);
Object result = load(context.createComponent(type, lifetime), context, lifetime);
if (!values.isEmpty()) {
// A second fx:root load uses the public FXMLLoader API for bean setters,
// enum/numeric coercion and diagnostics, without depending on BeanAdapter
@@ -137,19 +110,9 @@ final class Components {
}
}
/**
* Creates a new Component and loads its document.
* <p>
* The instance is not the cached singleton. Its dependencies still come from
* {@link ApplicationContext#getComponent}. Bindings wait until {@link #setModel} runs.
*
* @param type the Component class
* @param context the container that creates the instance and its dependencies
* @return the loaded Component
*/
static Object fresh(Class<?> type, ApplicationContext context, ViewLifetime lifetime) {
Object component = context.createComponent(type.asSubclass(Object.class));
return load(component, context, lifetime);
/** Creates a fresh Component and loads its document before setting its Model. */
static Object fresh(Class<?> type, ViewInstances context, ViewLifetime lifetime) {
return load(context.component(type, lifetime), context, lifetime);
}
/**
@@ -161,10 +124,6 @@ final class Components {
* @param model the Model instance
*/
static void setModel(Object component, Object model, ViewLifetime lifetime) {
if (!lifetime.managed()) {
modelProperty(component).setValue(model);
return;
}
LoadSession session = LoadSession.nest();
try {
modelProperty(component).setValue(model);
@@ -181,8 +140,7 @@ final class Components {
* @param context the container that creates nested Components
* @return the loaded Component
*/
private static Object load(Object component, ApplicationContext context, ViewLifetime lifetime) {
lifetime.ownController(component);
private static Object load(Object component, ViewInstances context, ViewLifetime lifetime) {
Class<?> type = component.getClass();
String document = type.getSimpleName() + ".fxml";
URL fxml = type.getResource(document);
@@ -195,11 +153,11 @@ final class Components {
FxmlHandlers.observe(loader, lifetime);
loader.setRoot(component);
loader.setController(component);
loader.setControllerFactory(nestedType -> ViewLoader.createController(context, nestedType, lifetime));
loader.setControllerFactory(nestedType -> context.controller(nestedType, lifetime));
loader.setBuilderFactory(nestedType -> builder(nestedType, context, lifetime));
loader.load();
nested.checkFailure();
if (lifetime.managed() && component instanceof Node node) {
if (component instanceof Node node) {
node.getProperties().put(Components.class, Boolean.TRUE);
lifetime.own(() -> node.getProperties().remove(Components.class));
}
@@ -221,7 +179,7 @@ final class Components {
* @param context the container that creates a named Converter
*/
private static void watchModel(Object component, List<BindingList> lists, Map<String, Object> namespace,
ApplicationContext context, ViewLifetime lifetime) {
ViewInstances context, ViewLifetime lifetime) {
Property<Object> model = modelProperty(component);
boolean[] applied = {false};
lifetime.listen(model, (observable, oldValue, newValue) -> {
@@ -239,10 +197,10 @@ final class Components {
for (BindingList list : lists) {
list.apply(namespace, viewModel, component, root, context, lifetime);
}
if (lifetime.managed()) Table.openAll(root, viewModel, context, lifetime);
Table.openAll(root, viewModel, context, lifetime);
} catch (RuntimeException | Error failure) {
lifetime.rollback(failure);
if (!lifetime.managed() || !LoadSession.recordFailure(failure)) {
if (!LoadSession.recordFailure(failure)) {
throw failure;
}
}
@@ -21,6 +21,12 @@ public final class DataGridColumn {
@Setter(lombok.AccessLevel.NONE)
private final java.util.Map<String, String> groupLabels = new java.util.LinkedHashMap<>();
/** Adds one FXML group label whose key can contain spaces, paths or other non-name characters. */
public static void setGroupLabel(DataGridColumn column, javafx.util.Pair<String, String> entry) {
column.groupLabels.put(java.util.Objects.requireNonNull(entry.getKey(), "group key"),
java.util.Objects.requireNonNull(entry.getValue(), "group label"));
}
private double width = 150;
private double minimumWidth = 80;
private double maximumWidth = 1200;
@@ -1,10 +1,10 @@
package de.neitzel.fx.view;
import de.neitzel.injection.ApplicationContext;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import javafx.beans.InvalidationListener;
import javafx.beans.property.Property;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
@@ -32,7 +32,7 @@ final class DirectBindingApplier {
* @param context the container that creates a named Converter
*/
static void apply(Map<String, Object> namespace, Object viewModel, DirectBinding binding,
ApplicationContext context, ViewLifetime lifetime) {
ViewInstances context, ViewLifetime lifetime) {
Object control = namespace.get(binding.getControl());
if (control == null) {
throw new IllegalArgumentException("No control \"" + binding.getControl() + "\"");
@@ -58,7 +58,8 @@ final class DirectBindingApplier {
return;
}
if (attribute.getValue() instanceof ObservableList<?> values) {
assignList(controlProperty, values, lifetime);
if ("view".equals(binding.getDirection())) alignTowardView(controlProperty, attribute, lifetime);
else assignList(controlProperty, values, lifetime);
return;
}
String converterName = binding.getConverter();
@@ -80,7 +81,7 @@ final class DirectBindingApplier {
/** Connects a named observable to the View when its accessor exposes no writable property. */
private static void alignReadOnly(Map<String, Object> namespace, Property<?> control, Resolved resolved,
DirectBinding binding, ApplicationContext context, ViewLifetime lifetime) {
DirectBinding binding, ViewInstances context, ViewLifetime lifetime) {
if (!"view".equals(binding.getDirection())) {
throw new IllegalArgumentException("Read-only source for path \"" + binding.getPath()
+ "\" requires direction=\"view\" on " + binding.getControl() + "." + binding.getProperty()
@@ -290,10 +291,10 @@ final class DirectBindingApplier {
* @param className the Converter class name
* @return the Converter
*/
private static Converter converter(ApplicationContext context, String className) {
private static Converter converter(ViewInstances context, String className) {
try {
Class<?> type = Class.forName(className);
Object instance = context.getComponent(type.asSubclass(Object.class));
Object instance = context.requiredService(type);
if (!(instance instanceof Converter created)) {
throw new IllegalArgumentException("Not a converter: " + className);
}
@@ -551,8 +552,17 @@ final class DirectBindingApplier {
private static void alignTowardView(Property<?> controlProperty, ObservableValue<?> attribute,
ViewLifetime lifetime) {
Property<Object> control = (Property<Object>) controlProperty;
Object previous = control.getValue();
control.setValue(attribute.getValue());
lifetime.listen(attribute, (observable, oldValue, newValue) -> control.setValue(newValue));
// ChangeListeners may suppress a new list whose elements equal the previous list.
InvalidationListener follow = ignored -> control.setValue(attribute.getValue());
attribute.addListener(follow);
lifetime.own(() -> {
attribute.removeListener(follow);
if ((previous instanceof ObservableList<?> || control.getValue() instanceof ObservableList<?>)
&& control.getValue() == attribute.getValue())
control.setValue(previous);
});
}
/**
@@ -20,7 +20,7 @@ final class FxmlHandlers implements LoadListener {
}
static void observe(FXMLLoader loader, ViewLifetime lifetime) {
if (lifetime.managed()) loader.setLoadListener(new FxmlHandlers(lifetime));
loader.setLoadListener(new FxmlHandlers(lifetime));
}
@Override
@@ -3,9 +3,7 @@ package de.neitzel.fx.view;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Holds the binding lists instantiated while one View is loading.
@@ -27,11 +25,6 @@ final class LoadSession {
*/
private final List<BindingList> bindingLists = new ArrayList<>();
/**
* Component classes already built during the outermost load.
*/
private final Set<Class<?>> built = new HashSet<>();
private Throwable bindingFailure;
// JavaFX reports exceptions from a property listener to the thread's uncaught handler.
@@ -105,23 +98,6 @@ final class LoadSession {
stack.peek().bindingLists.add(bindingList);
}
/**
* Records the first Component of {@code type} built during this load.
* <p>
* Nested documents share the outermost session, so a second Component of the same class
* anywhere in the load is not the first.
*
* @param type the Component class
* @return {@code true} when this is the first time that class is built during the load
*/
static boolean claimFirst(Class<?> type) {
Deque<LoadSession> stack = STACK.get();
if (stack == null || stack.isEmpty()) {
return true;
}
return stack.peekLast().built.add(type);
}
/**
* Returns the lists registered during this session, in document order.
*
@@ -1,6 +1,5 @@
package de.neitzel.fx.view;
import de.neitzel.injection.ApplicationContext;
import javafx.beans.property.Property;
import javafx.collections.ObservableList;
import javafx.scene.Node;
@@ -24,10 +23,10 @@ final class RepeatApplier {
/**
* Fills the named pane with one new Component for each element, in list order.
* <p>
* Each Component is a new injected instance. The cached singleton of that class is left
* in place. The child's model property is the element. Adding or removing an element
* adds or removes the matching child. The list is the one the entity holds, so a change
* on either side is visible in the pane.
* The adapter creates a fresh Component for each occurrence. Its model property is the
* element. Adding an element loads a child. Removing one releases that child's View.
* The list is the one the entity holds, so a change on either side is visible in the pane.
* The parent's View lifetime also owns the remaining children.
*
* @param namespace objects addressed by {@code fx:id}
* @param viewModel the ViewModel for this View, or a replacement that exposes the collection by name
@@ -35,7 +34,7 @@ final class RepeatApplier {
* @param context the container that creates each Component
*/
static void apply(Map<String, Object> namespace, Object viewModel, Repeat repeat,
ApplicationContext context, ViewLifetime lifetime) {
ViewInstances context, ViewLifetime lifetime) {
Object named = namespace.get(repeat.getPane());
if (!(named instanceof Pane pane)) {
throw new IllegalArgumentException("No pane \"" + repeat.getPane() + "\"");
@@ -82,7 +81,7 @@ final class RepeatApplier {
* @param values the collection
*/
@SuppressWarnings("unchecked")
private static void listen(Pane pane, Class<?> type, ApplicationContext context, ObservableList<?> values,
private static void listen(Pane pane, Class<?> type, ViewInstances context, ObservableList<?> values,
ViewLifetime lifetime, int offset, List<RepeatedChild> children) {
ObservableList<Object> elements = (ObservableList<Object>) values;
lifetime.listen(elements, change -> {
@@ -113,7 +112,7 @@ final class RepeatApplier {
* @param element the Model instance
* @return the loaded Component
*/
private static RepeatedChild child(Class<?> type, ApplicationContext context, Object element,
private static RepeatedChild child(Class<?> type, ViewInstances context, Object element,
ViewLifetime owner) {
ViewLifetime lifetime = owner.child();
try {
@@ -1,6 +1,5 @@
package de.neitzel.fx.view;
import de.neitzel.injection.ApplicationContext;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@@ -232,7 +231,7 @@ public class Table extends VBox {
/**
* The container that creates Rows.
*/
private ApplicationContext context;
private ViewInstances context;
/**
* The Row class.
@@ -363,7 +362,7 @@ public class Table extends VBox {
* @param viewModel the ViewModel for this View
* @param context the container that creates each Row
*/
static void openAll(Parent root, Object viewModel, ApplicationContext context, ViewLifetime lifetime) {
static void openAll(Parent root, Object viewModel, ViewInstances context, ViewLifetime lifetime) {
walk(root, root, viewModel, context, lifetime);
}
@@ -373,7 +372,7 @@ public class Table extends VBox {
* @param viewModel the ViewModel for this View
* @param context the container that creates each Row
*/
void open(Object viewModel, ApplicationContext context, ViewLifetime owner) {
void open(Object viewModel, ViewInstances context, ViewLifetime owner) {
if (resultMode) {
return;
}
@@ -1339,7 +1338,7 @@ public class Table extends VBox {
node.addEventFilter(MouseEvent.MOUSE_CLICKED, select);
rowLifetime.own(() -> node.removeEventFilter(MouseEvent.MOUSE_CLICKED, select));
watchEdits(node, rowLifetime);
if (rowLifetime.managed()) rowLifetimes.put(element, rowLifetime);
rowLifetimes.put(element, rowLifetime);
return node;
} catch (RuntimeException | Error failure) {
rowLifetime.rollback(failure);
@@ -1566,7 +1565,7 @@ public class Table extends VBox {
* @param viewModel the ViewModel for this View
* @param context the container that creates each Row
*/
private static void walk(Node node, Parent root, Object viewModel, ApplicationContext context,
private static void walk(Node node, Parent root, Object viewModel, ViewInstances context,
ViewLifetime lifetime) {
if (node != root && Components.ownsBindings(node)) return;
if (node instanceof Table table) {
@@ -0,0 +1,22 @@
package de.neitzel.fx.view;
import java.util.Optional;
/** Supplies a View's objects from the application's dependency injection configuration. */
public interface ViewDependencies {
/** Checks whether the exact FXML type is a Component, without creating an instance. */
boolean isComponent(Class<?> type);
/**
* Looks up an application-owned service such as a Converter or Localizer.
* Report lookup and creation failures as exceptions. An empty result means the service is absent.
*/
<T> Optional<T> findService(Class<T> type);
/**
* Creates a fresh Controller or Component and supplies its release action.
* The adapter owns any partial allocations until it returns the object.
*/
<T> ViewObject<T> createViewObject(Class<T> type);
}
@@ -0,0 +1,66 @@
package de.neitzel.fx.view;
import de.neitzel.fx.i18n.Localizer;
import java.util.Objects;
import java.util.Optional;
/** Instance selection shared by the FXML factories and the binding appliers. */
record ViewInstances(ViewDependencies dependencies) {
ViewInstances {
Objects.requireNonNull(dependencies, "View dependencies");
}
Object controller(Class<?> type, ViewLifetime lifetime) {
return create(type, lifetime);
}
boolean isComponent(Class<?> type) {
return dependencies.isComponent(type);
}
Object component(Class<?> type, ViewLifetime lifetime) {
if (!dependencies.isComponent(type)) {
throw new IllegalArgumentException("No Component registered for " + type.getName());
}
return createComponent(type, lifetime);
}
Object createComponent(Class<?> type, ViewLifetime lifetime) {
Object instance = create(type, lifetime);
if (instance.getClass() != type) {
throw new IllegalArgumentException("Expected exact Component type " + type.getName()
+ ", got " + instance.getClass().getName());
}
return instance;
}
private Object create(Class<?> type, ViewLifetime lifetime) {
try {
ViewObject<?> view = dependencies.createViewObject(type);
// Each instance owns a distinct cleanup entry even if actions are shared.
lifetime.own(() -> view.release().run());
return type.cast(view.instance());
} catch (RuntimeException failure) {
throw new IllegalStateException("Could not create View object " + type.getName(), failure);
}
}
Object requiredService(Class<?> type) {
return service(type)
.orElseThrow(() -> new IllegalArgumentException("No View service for " + type.getName()));
}
Localizer localizer() {
return service(Localizer.class).orElse(null);
}
private <T> Optional<T> service(Class<T> type) {
try {
return dependencies.findService(type);
} catch (RuntimeException failure) {
throw new IllegalStateException("Could not resolve View service " + type.getName(), failure);
}
}
}
@@ -22,31 +22,11 @@ final class ViewLifetime implements AutoCloseable {
return models;
}
boolean managed() {
return models != ViewModels.LEGACY;
}
void own(Runnable removal) {
if (managed()) {
if (closed) {
removal.run();
} else {
cleanup.addLast(removal);
}
}
}
void ownController(Object controller) {
if (controller instanceof AutoCloseable closeable) {
own(() -> {
try {
closeable.close();
} catch (RuntimeException failure) {
throw failure;
} catch (Exception failure) {
throw new IllegalStateException("Could not close " + controller.getClass().getName(), failure);
}
});
if (closed) {
removal.run();
} else {
cleanup.addLast(removal);
}
}
@@ -2,12 +2,12 @@ package de.neitzel.fx.view;
import de.neitzel.fx.i18n.Localizer;
import de.neitzel.fx.i18n.Messages;
import de.neitzel.injection.ApplicationContext;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import java.io.IOException;
import java.net.URL;
import java.util.Objects;
/**
* Loads a View for one Model instance.
@@ -21,80 +21,52 @@ public final class ViewLoader {
}
/**
* Loads a View for one Model instance.
* <p>
* Reuses the ViewModel already built for {@code model}, or builds one, then loads {@code fxml}
* and applies binding elements declared in {@code fx:define}. A Computed binding writes a
* Controller method result to a control and does not write the Model. Direction {@code both}
* keeps the control and the Attribute
* aligned, so editing the control writes the Attribute immediately. Direction {@code view}
* shows the Attribute and follows later property changes without writing the Attribute back.
* Direction {@code model} shows the current value, writes the Attribute when the control
* changes, and does not push later property changes to the control. A Path of one name is an
* Attribute of this View's ViewModel. Further names step into a nested ViewModel, and the
* direction applies to the last name. When a Complex attribute along the Path is null, the
* control and the Model keep their current values. A collection of simple values is one shared
* list: the Direct binding sets the control property to that
* {@link javafx.collections.ObservableList}, so an add or remove is visible on both sides.
* A path that is not a read-write Attribute fails the load. The context creates a Controller
* the document names, and injects that Controller's services. When the document names no
* Controller, the library supplies one. A Controller that implements {@link HasViewModel}
* receives the ViewModel after construction and before bindings. {@link ViewModelClass} on that
* Controller names the ViewModel class. The library constructs it with the Model instance
* before load. With no annotation, the library builds the generic ViewModel. The first View of a
* Model instance fixes that class. A later View that names a different class fails the load,
* and the earlier View stays as it was. A later View that names none reuses the ViewModel.
* The context creates a
* Converter when a Direct binding names one. A converter that cannot produce a value
* keeps the previous value and records one error Message on the ViewModel that owns the last
* Attribute, with that Attribute's name as the source. A parent carries a copy with the source
* extended. It does not fail the load.
* A parent document names a Component class as an element. The context creates that Component
* and injects its services. A second element of the same class is another injected instance,
* and the cached singleton stays the first one. The Component document {@code ClassName.fxml},
* in the same package, is loaded with the Component as {@code fx:root} and as the Controller.
* That document's bindings are not applied during this load. They run when the Component's
* model property becomes a non-null Model. {@link ViewModelClass} on the Component names the
* ViewModel class for that Model. A Component that implements {@link HasViewModel} receives
* that ViewModel after the property is set and before those bindings run.
* A {@link Repeat} in the same list names a pane, a Component class, and a collection
* Attribute. One new Component child is placed in that pane for each Model instance, in list
* order. Adding or removing an element updates that pane. Those instances are created with
* {@link de.neitzel.injection.ApplicationContext#createComponent} so the cached singleton of
* that class stays in place. A collection of Model instances is an
* {@link javafx.collections.ObservableList} of those instances, shared with the entity.
* Selection is a separate Attribute of the parent Model. Null means nothing is selected.
* A Direct binding can tie a control property to that Attribute. The repeated Component does
* not store the selection.
* Loading does not open a popup or fill a status bar. A Direct binding whose path is
* {@code latestMessage} shows the latest Message text. {@link MessagePopup#showNewMessages}
* shows each newly added Message in a dialog.
*
* @param fxml the FXML document
* @param model the Model instance
* @param context the application context
* Loads FXML with application-supplied dependencies and a managed Model context.
* Load and close the View on the JavaFX application thread. The caller owns the dependencies.
* @param fxml the FXML document
* @param model the Model instance
* @param dependencies the adapter for View objects and services
* @param models the Model context that owns the View
* @return the loaded View
* @throws IllegalArgumentException when a Direct binding names a path that is not a read-write Attribute
*/
public static LoadedView load(URL fxml, Object model, ApplicationContext context) {
return load(fxml, model, context, new ViewLifetime(ViewModels.LEGACY));
public static LoadedView loadWithDependencies(URL fxml, Object model,
ViewDependencies dependencies, ViewModelContext models) {
return load(fxml, model, new ViewInstances(dependencies), models.openView());
}
/**
* Loads a View with a fresh Controller and Components in an explicitly owned Model context.
* Close the result when its UI is removed, or close the Model context to close all its Views.
*
* @param fxml the FXML document
* @param model the Model instance
* @param context the container for Controllers and services
* @param models the Model context shared by this View and related Views
* @return the loaded View
* Loads a managed Component from its sibling ClassName.fxml on the JavaFX application thread.
* @param type the registered Component class
* @param model the initial non-null Model
* @param dependencies the adapter for View objects and services
* @param models the Model context that owns the View
* @return the initialized Component and its effective ViewModel
*/
public static LoadedView load(URL fxml, Object model, ApplicationContext context, ViewModelContext models) {
return load(fxml, model, context, models.openView());
public static LoadedView loadComponentWithDependencies(Class<? extends Parent> type, Object model,
ViewDependencies dependencies, ViewModelContext models) {
return loadComponent(type, model, new ViewInstances(dependencies), models);
}
private static LoadedView load(URL fxml, Object model, ApplicationContext context, ViewLifetime lifetime) {
private static LoadedView loadComponent(Class<? extends Parent> type, Object model,
ViewInstances context, ViewModelContext models) {
Objects.requireNonNull(model, "Component Model");
ViewLifetime lifetime = models.openView();
try {
Parent root = type.cast(Components.fresh(type, context, lifetime));
Components.setModel(root, model, lifetime);
Object viewModel = ViewModels.of(models, model, ViewModels.namedOn(type));
return new LoadedView(root, viewModel, lifetime);
} catch (RuntimeException | Error failure) {
lifetime.rollback(failure);
if (failure instanceof RuntimeException) {
throw new IllegalStateException("Could not load Component " + type.getName() + " from "
+ type.getSimpleName() + ".fxml: " + failure.getMessage(), failure);
}
throw failure;
}
}
private static LoadedView load(URL fxml, Object model, ViewInstances context, ViewLifetime lifetime) {
LoadSession session = LoadSession.nest();
try {
Class<?> controllerType = FxmlControllers.controllerClass(fxml);
@@ -102,7 +74,7 @@ public final class ViewLoader {
Object viewModel = ViewModels.of(lifetime.models(), model, viewModelClass);
FXMLLoader loader = new FXMLLoader(fxml, resources(context, fxml, controllerType));
FxmlHandlers.observe(loader, lifetime);
loader.setControllerFactory(type -> createController(context, type, lifetime));
loader.setControllerFactory(type -> context.controller(type, lifetime));
loader.setBuilderFactory(type -> Components.builder(type, context, lifetime));
Object loaded = loader.load();
if (!(loaded instanceof Parent root)) {
@@ -127,27 +99,17 @@ public final class ViewLoader {
throw new IllegalStateException("Could not load view " + fxml, failure);
} catch (RuntimeException | Error failure) {
lifetime.rollback(failure);
if (failure instanceof RuntimeException) {
throw new IllegalStateException("Could not load view " + fxml + ": " + failure.getMessage(), failure);
}
throw failure;
} finally {
LoadSession.unnest();
}
}
static Object createController(ApplicationContext context, Class<?> type, ViewLifetime lifetime) {
if (!lifetime.managed()) return context.getComponent(type);
Object controller = context.createComponent(type);
lifetime.ownController(controller);
return controller;
static Messages resources(ViewInstances context, URL fxml, Class<?> type) {
Localizer languages = context.localizer();
return languages == null ? null : languages.forView(fxml, type);
}
static Messages resources(ApplicationContext context, URL fxml, Class<?> type) {
Localizer languages;
try {
languages = context.getComponent(Localizer.class);
} catch (IllegalArgumentException unregistered) {
return null;
}
return languages.forView(fxml, type);
}
}
@@ -0,0 +1,15 @@
package de.neitzel.fx.view;
import java.util.Objects;
/**
* An instance and the action its View invokes once on release. Use an empty action when the
* instance has no cleanup. The action is responsible for any container-specific destruction.
*/
public record ViewObject<T>(T instance, Runnable release) {
public ViewObject {
Objects.requireNonNull(instance, "View object");
Objects.requireNonNull(release, "View object release action");
}
}
@@ -62,6 +62,39 @@ class HtmlViewerTest {
return (javafx.scene.control.Button) viewer.lookup(".html-viewer-media-load");
}
@Test void boundLocalTextReplacesPendingWorkAndDetachesOnClose() throws Exception {
var ref = new AtomicReference<HtmlViewer>();
var source = new javafx.beans.property.SimpleStringProperty("<p>First</p>");
var replacement = new javafx.beans.property.SimpleStringProperty("<p>Second</p>");
fx(() -> {
var viewer = new HtmlViewer();
ref.set(viewer);
viewer.htmlProperty().bind(source);
viewer.htmlProperty().bind(replacement);
source.set("<p>Detached</p>");
replacement.set("<p>Third</p>");
});
var viewer = ref.get();
try {
await(() -> !viewer.isLoading() && loaded(viewer) && browser(viewer).getEngine().getDocument()
.getDocumentElement().getTextContent().contains("Third"));
fx(() -> {
viewer.clear();
assertEquals("<p>Third</p>", replacement.get());
replacement.set(null);
replacement.set(" ");
assertNull(viewer.getError());
assertFalse(viewer.isExternalImagesAllowed());
replacement.set("<p>Pending</p>");
viewer.close();
assertFalse(viewer.htmlProperty().isBound());
replacement.set("<p>Too late</p>");
assertFalse(viewer.isLoading());
assertEquals("<p>Pending</p>", viewer.getHtml());
});
} finally { fx(viewer::close); }
}
@Test void ordinaryFxmlConstructsAnIdleLocalizableControl() throws Exception {
fx(() -> {
var loader = new javafx.fxml.FXMLLoader();
@@ -9,125 +9,53 @@ import de.neitzel.fx.docking.Dockable;
import de.neitzel.fx.docking.DockableId;
import de.neitzel.fx.docking.DockingManager;
import de.neitzel.fx.docking.DockingOptions;
import javafx.animation.AnimationTimer;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.geometry.Bounds;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.input.MouseButton;
import javafx.scene.robot.Robot;
import javafx.stage.Stage;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
/** Activating a background window is an applied action even when its selected tab stays the same. */
class ActivateDockingWindowTest {
@BeforeAll
static void startJavaFx() throws Exception {
FxThread.start();
FxThread.onFx(() -> Platform.setImplicitExit(false));
}
@Test
void activatingTheSameContentInABackgroundWindowReportsApplied() throws Exception {
AtomicReference<Fixture> state = new AtomicReference<>();
FxThread.onFx(() -> {
DockLayout initial = new DockLayout();
initial.setCenter(new DockGroupDefinition("editors"));
DockPane pane = new DockPane();
pane.setInitialLayout(initial);
Stage main = new Stage();
Stage main = spy(new Stage());
main.setScene(new Scene(pane, 480, 280));
DockingManager manager = DockingManager.attach(main, pane, new DockingOptions());
TextArea editor = new TextArea("Unsaved text");
Dockable dockable = new Dockable(new DockableId("notes"), editor);
manager.open(dockable, DockTarget.area("editors"));
Stage other = new Stage();
other.setScene(new Scene(new TextArea("Other window"), 240, 160));
state.set(new Fixture(main, other, manager, dockable));
main.show();
// Only the desktop's window state is simulated. Selection, scene focus and
// the activation result all come from the real controls and manager.
doReturn(true).when(main).isShowing();
doReturn(true).when(main).isFocused();
manager.activate(dockable.getId());
assertSame(dockable, manager.activeDockable());
assertSame(editor, main.getScene().getFocusOwner());
assertInstanceOf(ActionResult.NoChange.class, manager.activate(dockable.getId()));
doReturn(false).when(main).isFocused();
clearInvocations(main);
assertInstanceOf(ActionResult.Applied.class, manager.activate(dockable.getId()));
verify(main).requestFocus();
});
Fixture fixture = state.get();
try {
focus(fixture.main());
FxThread.onFx(() -> fixture.other().show());
focus(fixture.other());
FxThread.onFx(() -> {
assertFalse(fixture.main().isFocused());
assertSame(fixture.dockable(), fixture.manager().activeDockable());
assertSame(fixture.dockable().getContent(), fixture.main().getScene().getFocusOwner());
assertInstanceOf(ActionResult.Applied.class, fixture.manager().activate(fixture.dockable().getId()));
});
} finally {
FxThread.onFx(() -> {
fixture.other().hide();
fixture.main().hide();
});
}
}
private static void focus(Stage stage) throws Exception {
CountDownLatch focused = new CountDownLatch(1);
ChangeListener<Boolean> listener = (observable, old, current) -> {
if (current) focused.countDown();
};
AnimationTimer clickAfterDisplay = new AnimationTimer() {
private int pulses;
private long lastClick;
@Override
public void handle(long now) {
if (stage.isFocused()) {
focused.countDown();
stop();
return;
}
if (++pulses < 2) return;
if (now - lastClick < 250_000_000) return;
lastClick = now;
Bounds bounds = stage.getScene().getRoot().localToScreen(
stage.getScene().getRoot().getBoundsInLocal());
Robot robot = new Robot();
robot.mouseMove(bounds.getCenterX(), bounds.getCenterY());
robot.mouseClick(MouseButton.PRIMARY);
if (stage.isFocused()) focused.countDown();
}
};
FxThread.onFx(() -> {
stage.focusedProperty().addListener(listener);
stage.setAlwaysOnTop(true);
stage.toFront();
stage.requestFocus();
stage.getScene().getRoot().applyCss();
stage.getScene().getRoot().layout();
clickAfterDisplay.start();
});
try {
// A native click activates the application even if the previous test or
// another application owned desktop focus. RequestFocus alone cannot
// establish that precondition reliably on macOS. FX pulses do not
// guarantee that the native compositor has displayed the window;
// retry only this focus precondition within the bounded wait.
assertTrue(focused.await(5, TimeUnit.SECONDS), "Desktop did not focus the requested window");
} finally {
FxThread.onFx(() -> {
clickAfterDisplay.stop();
stage.focusedProperty().removeListener(listener);
stage.setAlwaysOnTop(false);
});
}
}
private record Fixture(Stage main, Stage other, DockingManager manager, Dockable dockable) { }
}
@@ -1,7 +1,6 @@
package de.neitzel.fx.view;
import de.neitzel.fx.view.command.CommandController;
import de.neitzel.injection.ApplicationContext;
import java.nio.file.Files;
import java.nio.file.Path;
import javafx.scene.control.Button;
@@ -35,7 +34,7 @@ class BindCommandTest {
""");
FxThread.onFx(() -> {
try (var models = new ViewModelContext()) {
var view = ViewLoader.load(url, new CommandController.Subject(), services(), models);
var view = ViewLoader.loadWithDependencies(url, new CommandController.Subject(), services(), models);
var model = (CommandController.Model) view.getViewModel();
var button = (Button) view.getRoot().lookup("#button");
var menu = ((MenuBar) view.getRoot().lookup("#menu")).getMenus().getFirst();
@@ -83,8 +82,8 @@ class BindCommandTest {
var url = view("invalid-command.fxml", scenario[0]);
FxThread.onFx(() -> {
try (var models = new ViewModelContext()) {
var failure = assertThrows(IllegalArgumentException.class,
() -> ViewLoader.load(url, new CommandController.Subject(), services(), models));
var failure = assertThrows(IllegalStateException.class,
() -> ViewLoader.loadWithDependencies(url, new CommandController.Subject(), services(), models));
assertTrue(failure.getMessage().contains("invalid-command.fxml"));
assertTrue(failure.getMessage().contains(scenario[1]));
}
@@ -92,8 +91,8 @@ class BindCommandTest {
}
}
private ApplicationContext services() {
return new ApplicationContext("de.neitzel.fx.view.command");
private TestViews services() {
return new TestViews();
}
private java.net.URL view(String name, String bindings) throws Exception {
@@ -2,7 +2,6 @@ package de.neitzel.fx.view;
import de.neitzel.fx.view.fixture.Person;
import de.neitzel.fx.view.readable.ReadableSourcesController.Sources;
import de.neitzel.injection.ApplicationContext;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
@@ -34,7 +33,7 @@ class BindReadOnlySourcesTest {
@Test
void followsOnlyDependenciesOfTheViewModelSource() throws Exception {
FxThread.onFx(() -> {
LoadedView view = ViewLoader.load(DOCUMENT, new Person("Ada"), context());
LoadedView view = TestViews.load(DOCUMENT, new Person("Ada"), context());
Sources sources = (Sources) view.getViewModel();
Button commit = (Button) view.getRoot().lookup("#commit");
Label title = (Label) view.getRoot().lookup("#title");
@@ -77,8 +76,8 @@ class BindReadOnlySourcesTest {
Files.writeString(invalid, fxml.replace("path=\"observableTitle\" direction=\"view\"",
"path=\"observableTitle\" direction=\"" + direction + "\""));
FxThread.onFx(() -> {
IllegalArgumentException failure = assertThrows(IllegalArgumentException.class,
() -> ViewLoader.load(invalid.toUri().toURL(), new Person("Ada"), context()));
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> TestViews.load(invalid.toUri().toURL(), new Person("Ada"), context()));
assertTrue(failure.getMessage().contains("Read-only source"), failure.getMessage());
assertTrue(failure.getMessage().contains("observableTitle"), failure.getMessage());
assertTrue(failure.getMessage().contains("caption.text"), failure.getMessage());
@@ -86,7 +85,7 @@ class BindReadOnlySourcesTest {
});
}
private static ApplicationContext context() {
return new ApplicationContext("de.neitzel.fx.view.readable");
private static TestViews context() {
return new TestViews();
}
}
@@ -3,7 +3,6 @@ package de.neitzel.fx.view;
import de.neitzel.fx.view.fixture.Address;
import de.neitzel.fx.view.fixture.Household;
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.TextField;
@@ -55,8 +54,8 @@ class CarryChildMessageTest {
person.setAddress(new Address("Main"));
URL fxml = CarryChildMessageTest.class.getResource("name-both-ways.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
ViewModel personModel = loaded.getViewModel();
ViewModel addressModel = (ViewModel) personModel.property("address").getValue();
addressModel.addMessage(new Message(Message.Severity.INFO, "lane is closed", "street"));
@@ -85,8 +84,8 @@ class CarryChildMessageTest {
household.setPerson(person);
URL fxml = CarryChildMessageTest.class.getResource("plain-view.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, household, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, household, context);
ViewModel householdModel = loaded.getViewModel();
ViewModel personModel = (ViewModel) householdModel.property("person").getValue();
ViewModel addressModel = (ViewModel) personModel.property("address").getValue();
@@ -112,8 +111,8 @@ class CarryChildMessageTest {
person.setAddress(new Address("Main"));
URL fxml = CarryChildMessageTest.class.getResource("address-street-converted.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
TextField streetField = (TextField) loaded.getRoot().lookup("#streetField");
streetField.setText("nope");
@@ -145,8 +144,8 @@ class CarryChildMessageTest {
person.setAddress(new Address("Main"));
URL fxml = CarryChildMessageTest.class.getResource("address-street-converted.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
TextField streetField = (TextField) loaded.getRoot().lookup("#streetField");
streetField.setText("nope");
streetField.setText("ok Oak");
@@ -173,8 +172,8 @@ class CarryChildMessageTest {
household.setPerson(person);
URL fxml = CarryChildMessageTest.class.getResource("household-street-converted.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, household, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, household, context);
TextField streetField = (TextField) loaded.getRoot().lookup("#streetField");
streetField.setText("nope");
@@ -217,8 +216,8 @@ class CarryChildMessageTest {
person.setAddress(new Address("Main"));
URL fxml = CarryChildMessageTest.class.getResource("plain-view.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
ViewModel personModel = loaded.getViewModel();
ViewModel addressModel = (ViewModel) personModel.property("address").getValue();
addressModel.addMessage(new Message(Message.Severity.INFO, "lane is closed", "street"));
@@ -235,7 +234,7 @@ class CarryChildMessageTest {
assertEquals("lane is closed", addressModel.getMessages().get(0).getText());
Address moved = new Address("Oak");
LoadedView movedView = ViewLoader.load(fxml, moved, context);
LoadedView movedView = TestViews.load(fxml, moved, context);
movedView.getViewModel().addMessage(new Message(Message.Severity.WARN, "under repair", "street"));
address.setValue(movedView.getViewModel());
@@ -259,8 +258,8 @@ class CarryChildMessageTest {
person.setAddress(new Address("Main"));
URL fxml = CarryChildMessageTest.class.getResource("address-street-converted.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
ViewModel personModel = loaded.getViewModel();
personModel.addMessage(new Message(Message.Severity.INFO, "keep me", "form"));
TextField streetField = (TextField) loaded.getRoot().lookup("#streetField");
@@ -304,8 +303,8 @@ class CarryChildMessageTest {
household.setPerson(person);
URL fxml = CarryChildMessageTest.class.getResource("household-street-converted.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, household, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, household, context);
TextField streetField = (TextField) loaded.getRoot().lookup("#streetField");
streetField.setText("nope");
streetField.setText("ok Oak");
@@ -335,8 +334,8 @@ class CarryChildMessageTest {
person.setWork(shared);
URL fxml = CarryChildMessageTest.class.getResource("plain-view.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
ViewModel personModel = loaded.getViewModel();
ViewModel homeModel = (ViewModel) personModel.property("home").getValue();
homeModel.addMessage(new Message(Message.Severity.INFO, "lane is closed", "street"));
@@ -2,7 +2,6 @@ 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;
@@ -51,8 +50,8 @@ class ChooseControllerAndViewModelTest {
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);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
Label handedLabel = (Label) loaded.getRoot().lookup("#handedLabel");
assertEquals("handed-Ada", handedLabel.getText());
});
@@ -67,8 +66,8 @@ class ChooseControllerAndViewModelTest {
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);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
Label deskLabel = (Label) loaded.getRoot().lookup("#deskLabel");
assertEquals("from-the-desk", deskLabel.getText());
});
@@ -83,8 +82,8 @@ class ChooseControllerAndViewModelTest {
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);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
Label titleLabel = (Label) loaded.getRoot().lookup("#titleLabel");
assertEquals("titled-Ada", titleLabel.getText());
@SuppressWarnings("unchecked")
@@ -105,8 +104,8 @@ class ChooseControllerAndViewModelTest {
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);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
Label badgeLabel = (Label) loaded.getRoot().lookup("#badgeLabel");
assertEquals("badge-Ada", badgeLabel.getText());
@SuppressWarnings("unchecked")
@@ -128,8 +127,8 @@ class ChooseControllerAndViewModelTest {
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);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
Label captionLabel = (Label) loaded.getRoot().lookup("#captionLabel");
assertEquals("caption-Main", captionLabel.getText());
});
@@ -146,12 +145,12 @@ class ChooseControllerAndViewModelTest {
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);
TestViews context = new TestViews();
LoadedView first = TestViews.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));
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> TestViews.load(badge, person, context));
assertTrue(failure.getMessage().contains("TitledViewModel"), failure.getMessage());
assertTrue(failure.getMessage().contains("BadgeViewModel"), failure.getMessage());
assertEquals("titled-Ada", titleLabel.getText());
@@ -169,9 +168,9 @@ class ChooseControllerAndViewModelTest {
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);
TestViews context = new TestViews();
LoadedView first = TestViews.load(named, person, context);
LoadedView second = TestViews.load(plain, person, context);
TextField firstName = (TextField) first.getRoot().lookup("#nameField");
TextField secondName = (TextField) second.getRoot().lookup("#nameField");
assertEquals("Ada", firstName.getText());
@@ -1,7 +1,6 @@
package de.neitzel.fx.view;
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;
@@ -49,8 +48,8 @@ class ComputeAValueTest {
person.setAge(36);
URL fxml = ComputeAValueTest.class.getResource("working-age.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.computed");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
Label workingAgeLabel = (Label) loaded.getRoot().lookup("#workingAgeLabel");
assertEquals("initial-age", workingAgeLabel.getText());
assertEquals("Ada", person.getName());
@@ -67,8 +66,8 @@ class ComputeAValueTest {
Person person = new Person("Ada");
URL fxml = ComputeAValueTest.class.getResource("working-age.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.computed");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
TextField nameField = (TextField) loaded.getRoot().lookup("#nameField");
Label workingAgeLabel = (Label) loaded.getRoot().lookup("#workingAgeLabel");
nameField.setText("Grace");
@@ -86,8 +85,8 @@ class ComputeAValueTest {
Person person = new Person("Ada");
URL fxml = ComputeAValueTest.class.getResource("working-age.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.computed");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
Label workingAgeLabel = (Label) loaded.getRoot().lookup("#workingAgeLabel");
@SuppressWarnings("unchecked")
Property<String> name = (Property<String>) loaded.property("name");
@@ -106,8 +105,8 @@ class ComputeAValueTest {
Person person = new Person("Ada");
URL fxml = ComputeAValueTest.class.getResource("working-age.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.computed");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
Label workingAgeLabel = (Label) loaded.getRoot().lookup("#workingAgeLabel");
assertEquals("initial-age", workingAgeLabel.getText());
workingAgeLabel.setText("sentinel");
@@ -1,7 +1,6 @@
package de.neitzel.fx.view;
import de.neitzel.fx.view.fixture.Person;
import de.neitzel.injection.ApplicationContext;
import javafx.application.Platform;
import javafx.beans.property.IntegerProperty;
import javafx.scene.control.Label;
@@ -56,8 +55,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
TextField ageField = (TextField) loaded.getRoot().lookup("#ageField");
assertEquals("years:42", ageField.getText());
});
@@ -73,8 +72,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
TextField ageField = (TextField) loaded.getRoot().lookup("#ageField");
ageField.setText("years:11");
assertEquals(11, person.getAge());
@@ -91,8 +90,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-view-converted.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
Label ageLabel = (Label) loaded.getRoot().lookup("#ageLabel");
assertEquals("shown 42", ageLabel.getText());
ageLabel.setText("shown 99");
@@ -110,8 +109,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-and-view-converted.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
TextField ageField = (TextField) loaded.getRoot().lookup("#ageField");
Label ageLabel = (Label) loaded.getRoot().lookup("#ageLabel");
assertEquals("shown 42", ageLabel.getText());
@@ -131,8 +130,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-model-converted.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
TextField ageField = (TextField) loaded.getRoot().lookup("#ageField");
assertEquals("years:42", ageField.getText());
((IntegerProperty) loaded.property("age")).set(7);
@@ -154,8 +153,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
TextField ageField = (TextField) loaded.getRoot().lookup("#ageField");
ageField.setText("nope");
assertEquals(Integer.valueOf(42), person.getAge());
@@ -180,8 +179,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
TextField ageField = (TextField) loaded.getRoot().lookup("#ageField");
ageField.setText("nope");
ViewModel viewModel = loaded.getViewModel();
@@ -205,8 +204,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
TextField ageField = (TextField) loaded.getRoot().lookup("#ageField");
ageField.setText("nope");
ageField.setText("years:11");
@@ -227,8 +226,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
TextField ageField = (TextField) loaded.getRoot().lookup("#ageField");
ViewModel viewModel = loaded.getViewModel();
ageField.setText("nope");
@@ -255,8 +254,8 @@ class ConvertAndRecordFailureTest {
person.setAge(42);
URL fxml = ConvertAndRecordFailureTest.class.getResource("age-both-converted.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
TextField ageField = (TextField) loaded.getRoot().lookup("#ageField");
ViewModel viewModel = loaded.getViewModel();
String log = captureErr(() -> {
@@ -6,7 +6,6 @@ import de.neitzel.fx.control.NonNegativeIntegerSpinner;
import de.neitzel.fx.control.StatusBar;
import de.neitzel.fx.docking.DockPane;
import de.neitzel.grid.*;
import de.neitzel.injection.ApplicationContext;
import javafx.collections.*;
import javafx.fxml.FXMLLoader;
@@ -55,6 +54,22 @@ class DataGridFxmlTest {
</DataGrid>
""";
@Test
void groupLabelEntriesRetainLiteralKeysAlongsideMapAttributes() throws IOException {
String xml = """
<?import de.neitzel.fx.view.DataGridColumn?>
<DataGridColumn>
<groupLabels Post="Postfach"/>
<DataGridColumn.groupLabel><javafx.util.Pair key="/" value="Wurzel"/></DataGridColumn.groupLabel>
<DataGridColumn.groupLabel><javafx.util.Pair key="Post/Eingang" value="Eingang"/></DataGridColumn.groupLabel>
<DataGridColumn.groupLabel><javafx.util.Pair key="Ohne Endung" value="Sonstige"/></DataGridColumn.groupLabel>
</DataGridColumn>
""";
DataGridColumn column = new FXMLLoader().load(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
assertEquals(Map.of("Post", "Postfach", "/", "Wurzel", "Post/Eingang", "Eingang", "Ohne Endung", "Sonstige"),
column.getGroupLabels());
}
@Test
void loadsReusableTagAndCompletionControls() throws Exception {
DataGridTest.fx(() -> {
@@ -225,10 +240,10 @@ class DataGridFxmlTest {
DataGridTest.fx(() -> {
try {
var view =
ViewLoader.load(
TestViews.load(
document.toUri().toURL(),
model,
new ApplicationContext("de.neitzel.fx.view.fixture"));
new TestViews());
@SuppressWarnings("unchecked")
var grid = (DataGrid<Long, Item>) view.getRoot().lookup("#grid");
ref.set(grid);
@@ -5,7 +5,6 @@ import de.neitzel.fx.view.component.Envelope;
import de.neitzel.fx.view.component.Letter;
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.scene.control.Label;
import javafx.scene.control.TextField;
@@ -55,8 +54,8 @@ class EditAddressInAComponentTest {
person.setAddress(address);
URL fxml = EditAddressInAComponentTest.class.getResource("address-component.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
AddressForm form = (AddressForm) loaded.getRoot().lookup("#addressForm");
assertNotNull(form);
assertSame(address, form.getModel());
@@ -76,8 +75,8 @@ class EditAddressInAComponentTest {
Person person = new Person("Ada");
URL fxml = EditAddressInAComponentTest.class.getResource("address-component.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
AddressForm form = (AddressForm) loaded.getRoot().lookup("#addressForm");
assertNotNull(form);
assertNull(form.getModel());
@@ -97,8 +96,8 @@ class EditAddressInAComponentTest {
person.setAddress(new Address("Main"));
URL fxml = EditAddressInAComponentTest.class.getResource("address-component.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
AddressForm form = (AddressForm) loaded.getRoot().lookup("#addressForm");
Label streetLabel = (Label) form.lookup("#streetLabel");
assertEquals("Lane", streetLabel.getText());
@@ -116,8 +115,8 @@ class EditAddressInAComponentTest {
person.setAddress(address);
URL fxml = EditAddressInAComponentTest.class.getResource("address-component.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
AddressForm form = (AddressForm) loaded.getRoot().lookup("#addressForm");
assertSame(loaded.property("address").getValue(), form.receivedViewModel());
assertEquals("kept", form.streetTextAtHandOff());
@@ -136,8 +135,8 @@ class EditAddressInAComponentTest {
Letter letter = new Letter(new Envelope(address));
URL fxml = EditAddressInAComponentTest.class.getResource("letter-envelope.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component");
LoadedView loaded = ViewLoader.load(fxml, letter, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, letter, context);
TextField streetField = (TextField) loaded.getRoot().lookup("#streetField");
assertEquals("Main", streetField.getText());
streetField.setText("Oak");
@@ -151,8 +150,8 @@ class EditAddressInAComponentTest {
@Test
void componentAttributesApplyAfterInitialization() throws Exception {
onFx(() -> {
var context = new ApplicationContext("de.neitzel.fx.view.component");
var loaded = ViewLoader.load(getClass().getResource("address-component-attributes.fxml"),
var context = new TestViews();
var loaded = TestViews.load(getClass().getResource("address-component-attributes.fxml"),
new Person("Ada"), context);
var first = (AddressForm) loaded.getRoot().lookup("#first");
var second = (AddressForm) loaded.getRoot().lookup("#second");
@@ -165,7 +164,7 @@ class EditAddressInAComponentTest {
assertSame(first.getModel(), second.getModel());
assertEquals("Second", second.getCaption());
assertEquals(280, second.getPrefWidth());
assertSame(first, context.getComponent(AddressForm.class));
org.junit.jupiter.api.Assertions.assertNotSame(first, second);
TextField field = (TextField) first.lookup("#streetField");
assertEquals("Main", field.getText());
field.setText("Oak");
@@ -180,9 +179,9 @@ class EditAddressInAComponentTest {
void invalidComponentAttributesFailTheLoad() throws Exception {
onFx(() -> {
for (String kind : java.util.List.of("unknown", "number")) {
var context = new ApplicationContext("de.neitzel.fx.view.component");
var context = new TestViews();
org.junit.jupiter.api.Assertions.assertThrows(IllegalStateException.class,
() -> ViewLoader.load(getClass().getResource("address-component-invalid-" + kind + ".fxml"),
() -> TestViews.load(getClass().getResource("address-component-invalid-" + kind + ".fxml"),
new Person("Ada"), context));
}
});
@@ -3,7 +3,6 @@ package de.neitzel.fx.view;
import de.neitzel.fx.view.component.VisitRow;
import de.neitzel.fx.view.fixture.Host;
import de.neitzel.fx.view.fixture.Visit;
import de.neitzel.injection.ApplicationContext;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.control.Button;
@@ -151,7 +150,7 @@ class FilterByChecklistTest {
private static LoadedView load(Host host) {
URL fxml = FilterByChecklistTest.class.getResource("show-visits-selection.fxml");
assertNotNull(fxml);
return ViewLoader.load(fxml, host, new ApplicationContext("de.neitzel.fx.view.component"));
return TestViews.load(fxml, host, new TestViews());
}
/**
@@ -3,7 +3,6 @@ package de.neitzel.fx.view;
import de.neitzel.fx.view.fixture.Host;
import de.neitzel.fx.view.fixture.Role;
import de.neitzel.fx.view.fixture.Visit;
import de.neitzel.injection.ApplicationContext;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
@@ -206,7 +205,7 @@ class FilterByComparisonTest {
private static LoadedView load(Host host) {
URL fxml = FilterByComparisonTest.class.getResource("show-two-tables.fxml");
assertNotNull(fxml);
return ViewLoader.load(fxml, host, new ApplicationContext("de.neitzel.fx.view.component"));
return TestViews.load(fxml, host, new TestViews());
}
/**
@@ -3,7 +3,6 @@ package de.neitzel.fx.view;
import de.neitzel.fx.view.component.ActionRow;
import de.neitzel.fx.view.fixture.Host;
import de.neitzel.fx.view.fixture.Visit;
import de.neitzel.injection.ApplicationContext;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.HBox;
@@ -67,7 +66,7 @@ class KeepAControlAfterTheColumnsTest {
assertNotNull(fxml);
Host host = new Host();
host.setVisits(new ArrayList<>(List.of(new Visit("Main", "Berlin"))));
LoadedView loaded = ViewLoader.load(fxml, host, new ApplicationContext("de.neitzel.fx.view.component"));
LoadedView loaded = TestViews.load(fxml, host, new TestViews());
return (Table) loaded.getRoot().lookup("#visitsTable");
}
@@ -0,0 +1,62 @@
package de.neitzel.fx.view;
import de.neitzel.fx.control.AutoCompleteTextField;
import java.util.Map;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.scene.control.ComboBox;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ListSourceBindingTest {
public static class Tags {
private final ListProperty<String> tags =
new SimpleListProperty<>(FXCollections.observableArrayList("First"));
public ListProperty<String> tagsProperty() { return tags; }
}
@BeforeAll static void toolkit() throws Exception { DataGridTest.start(); }
@Test void viewBindingTracksEqualListReplacementAndRestoresThePreviousItems() throws Exception {
DataGridTest.fx(() -> {
var model = new Tags();
var combo = new ComboBox<String>();
var previous = combo.getItems();
var binding = new DirectBinding();
binding.setControl("combo");
binding.setProperty("items");
binding.setPath("tags");
binding.setDirection("view");
try (var models = new ViewModelContext(); var lifetime = new ViewLifetime(models)) {
DirectBindingApplier.apply(Map.of("combo", combo), model, binding,
new ViewInstances(new TestViews()), lifetime);
assertSame(model.tags.get(), combo.getItems());
var replacement = FXCollections.observableArrayList("First");
model.tags.set(replacement);
assertSame(replacement, combo.getItems());
model.tags.set(null);
assertNull(combo.getItems());
}
assertSame(previous, combo.getItems());
model.tags.set(FXCollections.observableArrayList("Detached"));
assertSame(previous, combo.getItems());
});
}
@Test void ordinaryJavaFxBindingReturnsToFixedSuggestionsOnUnbind() throws Exception {
DataGridTest.fx(() -> {
var field = new AutoCompleteTextField();
field.getSuggestions().add("Fixed");
var model = new Tags();
field.suggestionsSourceProperty().bind(model.tags);
assertSame(model.tags.get(), field.getSuggestionsSource());
field.suggestionsSourceProperty().unbind();
assertNull(field.getSuggestionsSource());
model.tags.set(FXCollections.observableArrayList("Detached"));
assertNull(field.getSuggestionsSource());
assertEquals(java.util.List.of("Fixed"), field.getSuggestions());
});
}
}
@@ -5,7 +5,6 @@ import de.neitzel.fx.view.fixture.Host;
import de.neitzel.fx.view.fixture.Person;
import de.neitzel.fx.view.fixture.Visit;
import de.neitzel.fx.view.managed.ViewController;
import de.neitzel.injection.ApplicationContext;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
@@ -32,11 +31,11 @@ class ManagedViewTest {
void sharesViewModelWithinContextAndClosesOnlyTheRequestedView() throws Exception {
FxThread.onFx(() -> {
var model = new Person("Ada");
var injection = new ApplicationContext("de.neitzel.fx.view.managed");
var injection = new TestViews();
try (var models = new ViewModelContext(); var otherModels = new ViewModelContext()) {
var first = ViewLoader.load(fxml("managed-view.fxml"), model, injection, models);
var second = ViewLoader.load(fxml("managed-view.fxml"), model, injection, models);
var other = ViewLoader.load(fxml("managed-view.fxml"), model, injection, otherModels);
var first = ViewLoader.loadWithDependencies(fxml("managed-view.fxml"), model, injection, models);
var second = ViewLoader.loadWithDependencies(fxml("managed-view.fxml"), model, injection, models);
var other = ViewLoader.loadWithDependencies(fxml("managed-view.fxml"), model, injection, otherModels);
assertSame(first.getViewModel(), second.getViewModel());
assertNotSame(first.getViewModel(), other.getViewModel());
@@ -65,7 +64,7 @@ class ManagedViewTest {
assertEquals("Lin", model.getName());
assertEquals(1, secondController.getCloseCount());
assertThrows(IllegalStateException.class,
() -> ViewLoader.load(fxml("managed-view.fxml"), model, injection, models));
() -> ViewLoader.loadWithDependencies(fxml("managed-view.fxml"), model, injection, models));
}
});
}
@@ -74,18 +73,18 @@ class ManagedViewTest {
void failedBindingClosesControllerAndRollsBackEarlierBinding() throws Exception {
FxThread.onFx(() -> {
var model = new Person("Ada");
var injection = new ApplicationContext("de.neitzel.fx.view.managed");
var injection = new TestViews();
try (var models = new ViewModelContext()) {
var registry = injection.getComponent(ViewController.Registry.class);
assertThrows(IllegalArgumentException.class,
() -> ViewLoader.load(fxml("managed-invalid.fxml"), model, injection, models));
var registry = injection.findService(ViewController.Registry.class).orElseThrow();
assertThrows(IllegalStateException.class,
() -> ViewLoader.loadWithDependencies(fxml("managed-invalid.fxml"), model, injection, models));
var abandoned = registry.getLastCreated();
assertEquals(1, abandoned.getCloseCount());
assertNull(abandoned.getInput().getOnAction());
abandoned.getInput().setText("Detached");
assertEquals("Ada", model.getName());
var loaded = ViewLoader.load(fxml("managed-view.fxml"), model, injection, models);
var loaded = ViewLoader.loadWithDependencies(fxml("managed-view.fxml"), model, injection, models);
field(loaded.getRoot(), "#name").setText("Working");
assertEquals("Detached", abandoned.getInput().getText());
assertEquals("Working", model.getName());
@@ -93,6 +92,26 @@ class ManagedViewTest {
});
}
@Test
void opensAComponentDirectlyAndDetachesOnlyItsOwnBindings() throws Exception {
FxThread.onFx(() -> {
var model = new Address("Main");
var services = new TestViews();
var type = de.neitzel.fx.view.component.AddressForm.class;
try (var models = new ViewModelContext()) {
var first = ViewLoader.loadComponentWithDependencies(type, model, services, models);
var second = ViewLoader.loadComponentWithDependencies(type, model, services, models);
assertSame(first.getViewModel(), second.getViewModel());
var input = field(first.getRoot(), "#streetField");
input.setText("Shared");
assertEquals("Shared", field(second.getRoot(), "#streetField").getText());
first.close();
input.setText("Detached");
assertEquals("Shared", model.getStreet());
}
});
}
@Test
void removingARepeatChildDetachesItsBindings() throws Exception {
FxThread.onFx(() -> {
@@ -101,8 +120,8 @@ class ManagedViewTest {
var second = new Address("Water");
person.setAddresses(new ArrayList<>(List.of(first, second)));
try (var models = new ViewModelContext()) {
var context = new ApplicationContext("de.neitzel.fx.view.component");
var loaded = ViewLoader.load(fxml("repeat-addresses.fxml"), person, context, models);
var context = new TestViews();
var loaded = ViewLoader.loadWithDependencies(fxml("repeat-addresses.fxml"), person, context, models);
var pane = (VBox) loaded.getRoot().lookup("#addressPane");
var detached = field(pane.getChildren().getFirst(), "#streetField");
var active = field(pane.getChildren().getLast(), "#streetField");
@@ -128,8 +147,8 @@ class ManagedViewTest {
var visit = new Visit("Main", "Darmstadt");
host.setVisits(new ArrayList<>(List.of(visit)));
try (var models = new ViewModelContext()) {
var context = new ApplicationContext("de.neitzel.fx.view.component");
var loaded = ViewLoader.load(fxml("show-visits.fxml"), host, context, models);
var context = new TestViews();
var loaded = ViewLoader.loadWithDependencies(fxml("show-visits.fxml"), host, context, models);
var table = (Table) loaded.getRoot().lookup("#visitsTable");
var scroll = (ScrollPane) table.lookup("." + Table.SCROLL_STYLE);
var input = field(scroll.getContent(), "#streetField");
@@ -2,7 +2,6 @@ package de.neitzel.fx.view;
import de.neitzel.fx.view.DataGridTest.Item;
import de.neitzel.grid.TextFilter;
import de.neitzel.injection.ApplicationContext;
import javafx.scene.control.Label;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@@ -39,10 +38,10 @@ class ObserveGridSelectionTest {
var control = grid.get();
control.select(1L);
var document = getClass().getResource("grid-selection-summary.fxml");
var context = new ApplicationContext("de.neitzel.fx.view.selection");
var context = new TestViews();
try (var selection = control.observeSelection();
var models = new ViewModelContext();
var view = ViewLoader.load(document, selection, context, models)) {
var view = ViewLoader.loadWithDependencies(document, selection, context, models)) {
var initial = selection.getSelection();
var summary = (Label) view.getRoot().lookup("#summary");
assertEquals(List.of(1L), initial.selectedKeys());
@@ -2,7 +2,6 @@ package de.neitzel.fx.view;
import de.neitzel.fx.view.fixture.Host;
import de.neitzel.fx.view.fixture.Visit;
import de.neitzel.injection.ApplicationContext;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
@@ -87,7 +86,7 @@ class OpenAtAGivenWidthTest {
*/
@Test
void aWidthThatIsNotPositiveFailsToLoad() throws Exception {
FxThread.onFx(() -> assertThrows(IllegalArgumentException.class, () -> table("show-visits-bad-width.fxml")));
FxThread.onFx(() -> assertThrows(IllegalStateException.class, () -> table("show-visits-bad-width.fxml")));
}
/**
@@ -101,7 +100,7 @@ class OpenAtAGivenWidthTest {
assertNotNull(fxml);
Host host = new Host();
host.setVisits(new ArrayList<>(List.of(new Visit("Main", "Berlin"))));
LoadedView loaded = ViewLoader.load(fxml, host, new ApplicationContext("de.neitzel.fx.view.component"));
LoadedView loaded = TestViews.load(fxml, host, new TestViews());
return (Table) loaded.getRoot().lookup("#visitsTable");
}
@@ -4,7 +4,6 @@ import de.neitzel.fx.view.fixture.Address;
import de.neitzel.fx.view.fixture.ObjectHolder;
import de.neitzel.fx.view.fixture.Person;
import de.neitzel.fx.view.fixture.Role;
import de.neitzel.injection.ApplicationContext;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.scene.control.Label;
@@ -62,8 +61,8 @@ class ReachNestedAttributeTest {
person.setAddress(new Address("Main"));
URL fxml = ReachNestedAttributeTest.class.getResource("name-both-ways.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
Object addressValue = loaded.property("address").getValue();
assertInstanceOf(ViewModel.class, addressValue);
assertEquals("Main", ((ViewModel) addressValue).property("street").getValue());
@@ -81,8 +80,8 @@ class ReachNestedAttributeTest {
person.setAddress(address);
URL fxml = ReachNestedAttributeTest.class.getResource("address-street-both.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
TextField streetField = (TextField) loaded.getRoot().lookup("#streetField");
assertEquals("Main", streetField.getText());
streetField.setText("Oak");
@@ -101,8 +100,8 @@ class ReachNestedAttributeTest {
person.setAddress(address);
URL fxml = ReachNestedAttributeTest.class.getResource("address-street-both-and-view.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
TextField streetField = (TextField) loaded.getRoot().lookup("#streetField");
Label streetLabel = (Label) loaded.getRoot().lookup("#streetLabel");
assertEquals("Main", streetLabel.getText());
@@ -125,8 +124,8 @@ class ReachNestedAttributeTest {
person.setAddress(address);
URL fxml = ReachNestedAttributeTest.class.getResource("address-object.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
ObjectHolder addressHolder = (ObjectHolder) loaded.getRoot().lookup("#addressHolder");
assertSame(address, addressHolder.getValue());
Address moved = new Address("Oak");
@@ -144,8 +143,8 @@ class ReachNestedAttributeTest {
Person person = new Person("Ada");
URL fxml = ReachNestedAttributeTest.class.getResource("address-object.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
ObjectHolder addressHolder = (ObjectHolder) loaded.getRoot().lookup("#addressHolder");
assertNull(addressHolder.getValue());
assertNull(person.getAddress());
@@ -167,8 +166,8 @@ class ReachNestedAttributeTest {
Person person = new Person("Ada");
URL fxml = ReachNestedAttributeTest.class.getResource("address-street-kept.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
TextField streetField = (TextField) loaded.getRoot().lookup("#streetField");
assertEquals("kept", streetField.getText());
assertNull(person.getAddress());
@@ -184,8 +183,8 @@ class ReachNestedAttributeTest {
Person person = new Person("Ada");
URL fxml = ReachNestedAttributeTest.class.getResource("name-both-ways.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
assertNull(loaded.property("address").getValue());
});
}
@@ -202,8 +201,8 @@ class ReachNestedAttributeTest {
person.setWork(shared);
URL fxml = ReachNestedAttributeTest.class.getResource("home-work-street.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
assertSame(loaded.property("home").getValue(), loaded.property("work").getValue());
TextField homeField = (TextField) loaded.getRoot().lookup("#homeField");
TextField workField = (TextField) loaded.getRoot().lookup("#workField");
@@ -227,8 +226,8 @@ class ReachNestedAttributeTest {
person.setWork(work);
URL fxml = ReachNestedAttributeTest.class.getResource("home-work-street.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
assertNotSame(loaded.property("home").getValue(), loaded.property("work").getValue());
TextField homeField = (TextField) loaded.getRoot().lookup("#homeField");
TextField workField = (TextField) loaded.getRoot().lookup("#workField");
@@ -249,8 +248,8 @@ class ReachNestedAttributeTest {
person.setFriend(person);
URL fxml = ReachNestedAttributeTest.class.getResource("name-both-ways.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
assertSame(loaded.getViewModel(), loaded.property("friend").getValue());
});
}
@@ -267,8 +266,8 @@ class ReachNestedAttributeTest {
grace.setFriend(ada);
URL fxml = ReachNestedAttributeTest.class.getResource("name-both-ways.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, ada, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, ada, context);
ViewModel graceModel = (ViewModel) loaded.property("friend").getValue();
assertEquals("Grace", graceModel.property("name").getValue());
assertSame(loaded.getViewModel(), graceModel.property("friend").getValue());
@@ -292,8 +291,8 @@ class ReachNestedAttributeTest {
person.setHired(hired);
URL fxml = ReachNestedAttributeTest.class.getResource("name-both-ways.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
assertEquals(true, loaded.property("active").getValue());
assertSame(Role.ADMIN, loaded.property("role").getValue());
assertEquals(born, loaded.property("born").getValue());
@@ -314,8 +313,8 @@ class ReachNestedAttributeTest {
person.setTags(tags);
URL fxml = ReachNestedAttributeTest.class.getResource("name-both-ways.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
assertInstanceOf(ObservableList.class, loaded.property("tags").getValue());
@SuppressWarnings("unchecked")
ObservableList<String> shown = (ObservableList<String>) loaded.property("tags").getValue();
@@ -335,9 +334,9 @@ class ReachNestedAttributeTest {
Person person = new Person("Ada");
URL fxml = ReachNestedAttributeTest.class.getResource("name-both-ways.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView first = ViewLoader.load(fxml, person, context);
LoadedView second = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView first = TestViews.load(fxml, person, context);
LoadedView second = TestViews.load(fxml, person, context);
assertSame(first.getViewModel(), second.getViewModel());
TextField firstName = (TextField) first.getRoot().lookup("#nameField");
TextField secondName = (TextField) second.getRoot().lookup("#nameField");
@@ -3,7 +3,6 @@ package de.neitzel.fx.view;
import de.neitzel.fx.view.component.AddressForm;
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.collections.ObservableList;
import javafx.scene.control.ComboBox;
@@ -61,8 +60,8 @@ class RepeatAddressComponentsTest {
person.setAddresses(new ArrayList<>(List.of(main, oak)));
URL fxml = RepeatAddressComponentsTest.class.getResource("plain-view.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
assertInstanceOf(ObservableList.class, loaded.property("addresses").getValue());
@SuppressWarnings("unchecked")
ObservableList<Address> addresses = (ObservableList<Address>) loaded.property("addresses").getValue();
@@ -88,17 +87,13 @@ class RepeatAddressComponentsTest {
person.setAddresses(new ArrayList<>(List.of(main, oak)));
URL fxml = RepeatAddressComponentsTest.class.getResource("repeat-addresses.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component");
AddressForm cached = context.getComponent(AddressForm.class);
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
VBox pane = (VBox) loaded.getRoot().lookup("#addressPane");
assertEquals(2, pane.getChildren().size());
AddressForm first = (AddressForm) pane.getChildren().get(0);
AddressForm second = (AddressForm) pane.getChildren().get(1);
assertNotSame(first, second);
assertNotSame(cached, first);
assertNotSame(cached, second);
assertSame(cached, context.getComponent(AddressForm.class));
assertSame(main, first.getModel());
assertSame(oak, second.getModel());
assertEquals("Main", ((TextField) first.lookup("#streetField")).getText());
@@ -120,8 +115,8 @@ class RepeatAddressComponentsTest {
person.setAddresses(new ArrayList<>(List.of(main, oak)));
URL fxml = RepeatAddressComponentsTest.class.getResource("repeat-addresses.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
VBox pane = (VBox) loaded.getRoot().lookup("#addressPane");
@SuppressWarnings("unchecked")
ObservableList<Address> addresses = (ObservableList<Address>) loaded.property("addresses").getValue();
@@ -159,8 +154,8 @@ class RepeatAddressComponentsTest {
person.setSelectedAddress(oak);
URL fxml = RepeatAddressComponentsTest.class.getResource("repeat-addresses.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
@SuppressWarnings("unchecked")
ComboBox<Address> selection = (ComboBox<Address>) loaded.getRoot().lookup("#selection");
assertSame(oak, selection.getValue());
@@ -192,15 +187,13 @@ class RepeatAddressComponentsTest {
person.setWork(work);
URL fxml = RepeatAddressComponentsTest.class.getResource("two-address-forms.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component");
AddressForm cached = context.getComponent(AddressForm.class);
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
AddressForm homeForm = (AddressForm) loaded.getRoot().lookup("#homeForm");
AddressForm workForm = (AddressForm) loaded.getRoot().lookup("#workForm");
assertNotNull(homeForm);
assertNotNull(workForm);
assertNotSame(homeForm, workForm);
assertSame(cached, context.getComponent(AddressForm.class));
assertSame(home, homeForm.getModel());
assertSame(work, workForm.getModel());
assertEquals("Main", ((TextField) homeForm.lookup("#streetField")).getText());
@@ -2,7 +2,6 @@ package de.neitzel.fx.view;
import de.neitzel.fx.view.fixture.Host;
import de.neitzel.fx.view.fixture.Visit;
import de.neitzel.injection.ApplicationContext;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.MouseButton;
@@ -89,7 +88,7 @@ class ResizeAColumnTest {
private static Table table(Host host) {
URL fxml = ResizeAColumnTest.class.getResource("show-visits.fxml");
assertNotNull(fxml);
LoadedView loaded = ViewLoader.load(fxml, host, new ApplicationContext("de.neitzel.fx.view.component"));
LoadedView loaded = TestViews.load(fxml, host, new TestViews());
return (Table) loaded.getRoot().lookup("#visitsTable");
}
@@ -2,7 +2,6 @@ package de.neitzel.fx.view;
import de.neitzel.fx.view.fixture.Host;
import de.neitzel.fx.view.fixture.Visit;
import de.neitzel.injection.ApplicationContext;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
@@ -110,7 +109,7 @@ class SearchTheChecklistTest {
private static LoadedView load(Host host) {
URL fxml = SearchTheChecklistTest.class.getResource("show-visits.fxml");
assertNotNull(fxml);
return ViewLoader.load(fxml, host, new ApplicationContext("de.neitzel.fx.view.component"));
return TestViews.load(fxml, host, new TestViews());
}
/**
@@ -3,7 +3,6 @@ package de.neitzel.fx.view;
import de.neitzel.fx.view.component.VisitRow;
import de.neitzel.fx.view.fixture.Host;
import de.neitzel.fx.view.fixture.Visit;
import de.neitzel.injection.ApplicationContext;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
@@ -107,7 +106,7 @@ class SelectARowTest {
private static LoadedView load(Host host) {
URL fxml = SelectARowTest.class.getResource("show-visits-selection.fxml");
assertNotNull(fxml);
return ViewLoader.load(fxml, host, new ApplicationContext("de.neitzel.fx.view.component"));
return TestViews.load(fxml, host, new TestViews());
}
/**
@@ -1,7 +1,6 @@
package de.neitzel.fx.view;
import de.neitzel.fx.view.fixture.Person;
import de.neitzel.injection.ApplicationContext;
import javafx.application.Platform;
import javafx.scene.control.ListView;
import javafx.scene.layout.VBox;
@@ -51,8 +50,8 @@ class ShowAListOfSimpleValuesTest {
person.setTags(new ArrayList<>(List.of("red", "blue")));
URL fxml = ShowAListOfSimpleValuesTest.class.getResource("tags-both-ways.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
VBox root = (VBox) loaded.getRoot();
assertEquals(1, root.getChildren().size());
@SuppressWarnings("unchecked")
@@ -4,7 +4,6 @@ import de.neitzel.fx.view.component.CityFirstRow;
import de.neitzel.fx.view.component.VisitRow;
import de.neitzel.fx.view.fixture.Host;
import de.neitzel.fx.view.fixture.Visit;
import de.neitzel.injection.ApplicationContext;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.scene.Parent;
@@ -191,7 +190,7 @@ class ShowATableOfRowsTest {
void aTableWithNoColumnFailsToLoad() throws Exception {
onFx(() -> {
Host host = host(new Visit("Main", "Berlin"));
assertThrows(IllegalArgumentException.class, () -> load("show-visits-no-column.fxml", host));
assertThrows(IllegalStateException.class, () -> load("show-visits-no-column.fxml", host));
});
}
@@ -202,7 +201,7 @@ class ShowATableOfRowsTest {
void aRepeatedAttributeFailsToLoad() throws Exception {
onFx(() -> {
Host host = host(new Visit("Main", "Berlin"));
assertThrows(IllegalArgumentException.class, () -> load("show-visits-duplicate.fxml", host));
assertThrows(IllegalStateException.class, () -> load("show-visits-duplicate.fxml", host));
});
}
@@ -213,7 +212,7 @@ class ShowATableOfRowsTest {
void aComplexAttributeFailsToLoad() throws Exception {
onFx(() -> {
Host host = host(new Visit("Main", "Berlin"));
assertThrows(IllegalArgumentException.class, () -> load("show-visits-complex.fxml", host));
assertThrows(IllegalStateException.class, () -> load("show-visits-complex.fxml", host));
});
}
@@ -227,8 +226,8 @@ class ShowATableOfRowsTest {
private static LoadedView load(String name, Host host) {
URL fxml = ShowATableOfRowsTest.class.getResource(name);
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.component");
return ViewLoader.load(fxml, host, context);
TestViews context = new TestViews();
return TestViews.load(fxml, host, context);
}
/**
@@ -1,7 +1,6 @@
package de.neitzel.fx.view;
import de.neitzel.fx.view.fixture.Person;
import de.neitzel.injection.ApplicationContext;
import javafx.application.Platform;
import javafx.beans.property.IntegerProperty;
import javafx.scene.control.Label;
@@ -51,8 +50,8 @@ class ShowAndEditOneAttributeTest {
Person person = new Person("Ada");
URL fxml = ShowAndEditOneAttributeTest.class.getResource("name-both-ways.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
TextField nameField = (TextField) loaded.getRoot().lookup("#nameField");
assertEquals("Ada", nameField.getText());
nameField.setText("Grace");
@@ -69,8 +68,8 @@ class ShowAndEditOneAttributeTest {
Person person = new Person("Ada");
URL fxml = ShowAndEditOneAttributeTest.class.getResource("name-both-and-view.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
TextField nameField = (TextField) loaded.getRoot().lookup("#nameField");
Label nameLabel = (Label) loaded.getRoot().lookup("#nameLabel");
assertEquals("Ada", nameLabel.getText());
@@ -91,8 +90,8 @@ class ShowAndEditOneAttributeTest {
Person person = new Person("Ada");
URL fxml = ShowAndEditOneAttributeTest.class.getResource("name-both-ways.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
person.setName("Grace");
TextField nameField = (TextField) loaded.getRoot().lookup("#nameField");
assertEquals("Ada", nameField.getText());
@@ -108,9 +107,9 @@ class ShowAndEditOneAttributeTest {
Person person = new Person("Ada");
URL fxml = ShowAndEditOneAttributeTest.class.getResource("read-only-title.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
IllegalArgumentException failure = assertThrows(IllegalArgumentException.class,
() -> ViewLoader.load(fxml, person, context));
TestViews context = new TestViews();
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> TestViews.load(fxml, person, context));
assertTrue(failure.getMessage().contains("title"));
});
}
@@ -124,9 +123,9 @@ class ShowAndEditOneAttributeTest {
Person person = new Person("Ada");
URL fxml = ShowAndEditOneAttributeTest.class.getResource("object-class.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
IllegalArgumentException failure = assertThrows(IllegalArgumentException.class,
() -> ViewLoader.load(fxml, person, context));
TestViews context = new TestViews();
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> TestViews.load(fxml, person, context));
assertTrue(failure.getMessage().contains("class"));
});
}
@@ -140,8 +139,8 @@ class ShowAndEditOneAttributeTest {
Person person = new Person("Ada");
URL fxml = ShowAndEditOneAttributeTest.class.getResource("name-both-ways.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
assertInstanceOf(IntegerProperty.class, loaded.property("age"));
});
}
@@ -1,7 +1,6 @@
package de.neitzel.fx.view;
import de.neitzel.fx.view.fixture.Person;
import de.neitzel.injection.ApplicationContext;
import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.Parent;
@@ -60,8 +59,8 @@ class ShowMessagesWhenAskedTest {
Person person = new Person("Ada");
URL fxml = ShowMessagesWhenAskedTest.class.getResource("name-both-ways.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
Parent root = loaded.getRoot();
Set<Node> nodesBefore = new HashSet<>(root.lookupAll("*"));
Set<Window> windowsBefore = snapshotWindows();
@@ -82,8 +81,8 @@ class ShowMessagesWhenAskedTest {
Person person = new Person("Ada");
URL fxml = ShowMessagesWhenAskedTest.class.getResource("latest-message.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
Label messageLabel = (Label) loaded.getRoot().lookup("#messageLabel");
loaded.getViewModel().addMessage(
new Message(Message.Severity.INFO, "saved the person", "form"));
@@ -103,8 +102,8 @@ class ShowMessagesWhenAskedTest {
Person person = new Person("Ada");
URL fxml = ShowMessagesWhenAskedTest.class.getResource("name-both-ways.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
Set<Window> windowsBefore = snapshotWindows();
MessagePopup.showNewMessages(loaded.getViewModel());
assertEquals(windowsBefore, snapshotWindows());
@@ -129,8 +128,8 @@ class ShowMessagesWhenAskedTest {
person.setAge(42);
URL fxml = ShowMessagesWhenAskedTest.class.getResource("age-both-converted.fxml");
assertNotNull(fxml);
ApplicationContext context = new ApplicationContext("de.neitzel.fx.view.fixture");
LoadedView loaded = ViewLoader.load(fxml, person, context);
TestViews context = new TestViews();
LoadedView loaded = TestViews.load(fxml, person, context);
TextField ageField = (TextField) loaded.getRoot().lookup("#ageField");
Set<Window> windowsBefore = snapshotWindows();
MessagePopup.showNewMessages(loaded.getViewModel());
@@ -4,7 +4,6 @@ import de.neitzel.fx.view.component.VisitRow;
import de.neitzel.fx.view.fixture.Host;
import de.neitzel.fx.view.fixture.Role;
import de.neitzel.fx.view.fixture.Visit;
import de.neitzel.injection.ApplicationContext;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
@@ -148,7 +147,7 @@ class SortOneColumnTest {
private static LoadedView load(String name, Host host) {
URL fxml = SortOneColumnTest.class.getResource(name);
assertNotNull(fxml);
return ViewLoader.load(fxml, host, new ApplicationContext("de.neitzel.fx.view.component"));
return TestViews.load(fxml, host, new TestViews());
}
/**
@@ -0,0 +1,87 @@
package de.neitzel.fx.view;
import de.neitzel.fx.view.chosen.BadgeController;
import de.neitzel.fx.view.chosen.CaptionAddressForm;
import de.neitzel.fx.view.chosen.DeskController;
import de.neitzel.fx.view.chosen.DeskGreeting;
import de.neitzel.fx.view.chosen.HandedNameController;
import de.neitzel.fx.view.chosen.TitledController;
import de.neitzel.fx.view.command.CommandController;
import de.neitzel.fx.view.component.ActionRow;
import de.neitzel.fx.view.component.AddressForm;
import de.neitzel.fx.view.component.CityFirstRow;
import de.neitzel.fx.view.component.EnvelopeForm;
import de.neitzel.fx.view.component.StreetCaption;
import de.neitzel.fx.view.component.VisitRow;
import de.neitzel.fx.view.computed.WorkingAgeController;
import de.neitzel.fx.view.fixture.AgeUnit;
import de.neitzel.fx.view.fixture.CheckedStreetConverter;
import de.neitzel.fx.view.fixture.PrefixedAgeConverter;
import de.neitzel.fx.view.fixture.ShownAgeConverter;
import de.neitzel.fx.view.managed.ViewController;
import de.neitzel.fx.view.readable.ReadableSourcesController;
import de.neitzel.fx.view.selection.SelectionSummaryController;
import java.net.URL;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
/** Explicit registration for the FX tests. Each test shares Models only within its own context. */
final class TestViews implements ViewDependencies {
private static final Set<Class<?>> COMPONENTS = Set.of(ActionRow.class, AddressForm.class,
CaptionAddressForm.class, CityFirstRow.class, EnvelopeForm.class, VisitRow.class);
private final ViewModelContext models = new ViewModelContext();
private final ViewController.Registry registry = new ViewController.Registry();
private final StreetCaption captions = new StreetCaption();
private final DeskGreeting greeting = new DeskGreeting();
private final Map<Class<?>, Object> services = Map.of(
ViewController.Registry.class, registry,
CheckedStreetConverter.class, new CheckedStreetConverter(),
PrefixedAgeConverter.class, new PrefixedAgeConverter(new AgeUnit()),
ShownAgeConverter.class, new ShownAgeConverter(),
ReadableSourcesController.Caption.class, new ReadableSourcesController.Caption());
private final Map<Class<?>, Supplier<?>> factories = Map.ofEntries(
Map.entry(ActionRow.class, ActionRow::new),
Map.entry(AddressForm.class, () -> new AddressForm(captions)),
Map.entry(BadgeController.class, BadgeController::new),
Map.entry(CaptionAddressForm.class, CaptionAddressForm::new),
Map.entry(CityFirstRow.class, CityFirstRow::new),
Map.entry(CommandController.class, CommandController::new),
Map.entry(DeskController.class, () -> new DeskController(greeting)),
Map.entry(EnvelopeForm.class, EnvelopeForm::new),
Map.entry(HandedNameController.class, HandedNameController::new),
Map.entry(ReadableSourcesController.class, ReadableSourcesController::new),
Map.entry(SelectionSummaryController.class, SelectionSummaryController::new),
Map.entry(TitledController.class, TitledController::new),
Map.entry(ViewController.class, () -> new ViewController(registry)),
Map.entry(VisitRow.class, VisitRow::new),
Map.entry(WorkingAgeController.class, WorkingAgeController::new));
static LoadedView load(URL fxml, Object model, TestViews dependencies) {
return ViewLoader.loadWithDependencies(fxml, model, dependencies, dependencies.models);
}
@Override
public boolean isComponent(Class<?> type) {
return COMPONENTS.contains(type);
}
@Override
public <T> Optional<T> findService(Class<T> type) {
return Optional.ofNullable(services.get(type)).map(type::cast);
}
@Override
public <T> ViewObject<T> createViewObject(Class<T> type) {
Supplier<?> factory = factories.get(type);
if (factory == null) throw new IllegalArgumentException("Unregistered test View type " + type.getName());
T object = type.cast(factory.get());
return new ViewObject<>(object, () -> {
if (object instanceof ViewController controller) controller.close();
});
}
}
@@ -0,0 +1,198 @@
package de.neitzel.fx.view;
import de.neitzel.fx.i18n.Localizer;
import de.neitzel.fx.view.component.AddressForm;
import de.neitzel.fx.view.component.StreetCaption;
import de.neitzel.fx.view.component.VisitRow;
import de.neitzel.fx.view.fixture.Address;
import de.neitzel.fx.view.fixture.AgeUnit;
import de.neitzel.fx.view.fixture.Host;
import de.neitzel.fx.view.fixture.Person;
import de.neitzel.fx.view.fixture.PrefixedAgeConverter;
import de.neitzel.fx.view.fixture.Visit;
import de.neitzel.fx.view.managed.ViewController;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ViewDependenciesTest {
@BeforeAll
static void startFx() throws InterruptedException {
FxThread.start();
}
@Test
void createsControllersForEachViewAndIncludeAndReleasesEachOnce() throws Exception {
FxThread.onFx(() -> {
var source = new Dependencies();
try (var models = new ViewModelContext()) {
var first = load("adapter-view.fxml", new Person("Ada"), source, models);
var second = load("adapter-view.fxml", new Person("Grace"), source, models);
var parent = controller(first, "#parent");
var included = controller(first, "#included");
var other = controller(second, "#parent");
assertEquals(4, source.releases.size());
assertNotSame(parent, included);
assertNotSame(parent, other);
first.close();
first.close();
assertEquals(1, source.releases.get(parent));
assertEquals(1, source.releases.get(included));
assertEquals(0, source.releases.get(other));
assertEquals(0, parent.getCloseCount());
assertSame(source.registry, source.findService(ViewController.Registry.class).orElseThrow());
}
assertTrue(source.releases.values().stream().allMatch(count -> count == 1));
});
}
@Test
void createsExactComponentsAndReleasesChildrenAsTheirModelsAreRemoved() throws Exception {
FxThread.onFx(() -> {
var source = new Dependencies();
var person = new Person("Ada");
person.setAddresses(new ArrayList<>(List.of(new Address("Main"))));
var host = new Host();
host.setVisits(new ArrayList<>(List.of(new Visit("Main", "Darmstadt"))));
try (var models = new ViewModelContext()) {
load("repeat-addresses.fxml", person, source, models);
load("show-visits.fxml", host, source, models);
var address = source.releases.keySet().stream().filter(AddressForm.class::isInstance)
.map(AddressForm.class::cast).findFirst().orElseThrow();
var row = source.releases.keySet().stream().filter(VisitRow.class::isInstance)
.findFirst().orElseThrow();
assertEquals("Lane", address.getCaption());
assertNotNull(address.receivedViewModel());
assertEquals("kept", address.streetTextAtHandOff());
person.getAddresses().clear();
host.getVisits().clear();
assertEquals(1, source.releases.get(address));
assertEquals(1, source.releases.get(row));
var standalone = ViewLoader.loadComponentWithDependencies(
AddressForm.class, new Address("New"), source, models);
assertNotSame(address, standalone.getRoot());
source.addressFactory = ignored -> new AddressForm(new StreetCaption()) {};
var wrong = assertThrows(IllegalStateException.class, () ->
ViewLoader.loadComponentWithDependencies(AddressForm.class, new Address("Bad"), source, models));
assertTrue(wrong.getMessage().contains("Expected exact Component type"));
source.addressFactory = null;
var missing = assertThrows(IllegalStateException.class, () ->
ViewLoader.loadComponentWithDependencies(AddressForm.class, new Address("Bad"), source, models));
assertTrue(missing.getMessage().contains("No Component registered"));
}
assertTrue(source.releases.values().stream().allMatch(count -> count == 1));
});
}
@Test
void rollsBackEveryAcquiredObjectWhenAComponentLoadFails() throws Exception {
FxThread.onFx(() -> {
var source = new Dependencies();
source.failOnRelease = true;
try (var models = new ViewModelContext()) {
var failure = assertThrows(IllegalStateException.class, () ->
load("adapter-invalid.fxml", new Person("Ada"), source, models));
assertTrue(failure.getMessage().contains("adapter-invalid.fxml"));
assertTrue(failure.getCause().getSuppressed().length > 0);
assertEquals(2, source.releases.size());
assertTrue(source.releases.values().stream().allMatch(count -> count == 1));
}
});
}
@Test
void resolvesConvertersAndDistinguishesMissingServicesFromLookupFailure() throws Exception {
FxThread.onFx(() -> {
var source = new Dependencies();
var person = new Person("Ada");
person.setAge(24);
try (var models = new ViewModelContext()) {
var loaded = load("age-both-converted.fxml", person, source, models);
var fields = ((VBox) loaded.getRoot()).getChildren();
assertEquals(new AgeUnit().prefix() + 24, ((TextField) fields.getFirst()).getText());
source.services.remove(PrefixedAgeConverter.class);
var missing = assertThrows(IllegalStateException.class, () ->
load("age-both-converted.fxml", person, source, models));
assertTrue(missing.getMessage().contains(PrefixedAgeConverter.class.getName()));
source.services.put(Localizer.class, new Localizer(Locale.GERMAN, Locale.ENGLISH,
new Localizer.Catalog(getClass(), "LocalizerTestApp")));
var localized = load("adapter-localized.fxml", person, source, models);
assertEquals("Application", localized.getRoot().getAccessibleText());
source.lookupFailure = new IllegalArgumentException("Ambiguous Localizer");
var unavailable = assertThrows(IllegalStateException.class, () ->
load("adapter-view.fxml", person, source, models));
assertTrue(unavailable.getMessage().contains(Localizer.class.getName()));
assertSame(source.lookupFailure, unavailable.getCause().getCause());
}
});
}
private static ViewController controller(LoadedView view, String id) {
return (ViewController) view.getRoot().lookup(id).getUserData();
}
private static LoadedView load(String resource, Object model, ViewDependencies source, ViewModelContext models) {
URL fxml = ViewDependenciesTest.class.getResource(resource);
return ViewLoader.loadWithDependencies(fxml, model, source, models);
}
private static final class Dependencies implements ViewDependencies {
private final ViewController.Registry registry = new ViewController.Registry();
private final Map<Class<?>, Object> services = new HashMap<>(Map.of(
ViewController.Registry.class, registry,
PrefixedAgeConverter.class, new PrefixedAgeConverter(new AgeUnit())));
private final Map<Object, Integer> releases = new IdentityHashMap<>();
private Function<StreetCaption, AddressForm> addressFactory = AddressForm::new;
private RuntimeException lookupFailure;
private boolean failOnRelease;
@Override
public boolean isComponent(Class<?> type) {
return type == VisitRow.class || (type == AddressForm.class && addressFactory != null);
}
@Override
public <T> Optional<T> findService(Class<T> type) {
if (type == Localizer.class && lookupFailure != null) throw lookupFailure;
return Optional.ofNullable(services.get(type)).map(type::cast);
}
@Override
public <T> ViewObject<T> createViewObject(Class<T> type) {
Object instance;
if (type == ViewController.class) {
instance = new ViewController(registry);
} else if (type == AddressForm.class) {
instance = addressFactory.apply(new StreetCaption());
} else if (type == VisitRow.class) {
instance = new VisitRow();
} else {
throw new AssertionError("Unexpected DI type " + type);
}
releases.put(instance, 0);
return new ViewObject<>(type.cast(instance), () -> {
releases.merge(instance, 1, Integer::sum);
if (failOnRelease) throw new IllegalStateException("release failed");
});
}
}
}
@@ -1,12 +1,11 @@
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 {
}
@@ -1,7 +1,6 @@
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;
@@ -9,7 +8,7 @@ import javafx.scene.layout.VBox;
/**
* Component that names {@link StreetTitleViewModel} for the address it shows.
*/
@Singleton
@ViewModelClass(StreetTitleViewModel.class)
public class CaptionAddressForm extends VBox {
@@ -1,12 +1,10 @@
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 {
/**
@@ -19,7 +17,7 @@ public class DeskController {
*
* @param greeting the service that supplies the greeting
*/
@Inject
public DeskController(DeskGreeting greeting) {
this.greeting = greeting;
}
@@ -1,11 +1,10 @@
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 {
/**
@@ -2,12 +2,11 @@ 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 {
/**
@@ -1,12 +1,11 @@
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 {
}
@@ -3,12 +3,11 @@ package de.neitzel.fx.view.command;
import de.neitzel.fx.view.Command;
import de.neitzel.fx.view.ViewModel;
import de.neitzel.fx.view.ViewModelClass;
import jakarta.inject.Named;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import lombok.Getter;
@Named
@ViewModelClass(CommandController.Model.class)
public final class CommandController {
@@ -1,7 +1,5 @@
package de.neitzel.fx.view.component;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.layout.HBox;
@@ -9,7 +7,7 @@ import javafx.scene.layout.HBox;
/**
* A Row with street and city fields and a control after them.
*/
@Singleton
public class ActionRow extends HBox {
/**
@@ -20,7 +18,7 @@ public class ActionRow extends HBox {
/**
* Creates a row.
*/
@Inject
public ActionRow() {
}

Some files were not shown because too many files have changed in this diff Show More