Add introductory JavaFX contact book and Designer tutorial
Co-authored-by: Junie <junie@jetbrains.com>
This commit is contained in:
@@ -2,10 +2,11 @@
|
||||
|
||||
Neitzel FX Designer edits ordinary FXML while understanding NeitzelLib Models, bindings and reusable Components. The standalone application and the IntelliJ editor share the same Scene Builder Kit UI. This guide describes the current implementation; the older work-package documents record implementation history and test evidence.
|
||||
|
||||
Start with the [Person desk quick start](quick-start.md). It uses the real `fx-example` module in NeitzelLib, rather than a separate imitation. The module shows direct and computed bindings, converters, nested/repeated Components, a Table, selection, messages and dependency injection. The optional Designer profile adds sample previews and generated metadata without putting the Designer in the application's runtime dependencies.
|
||||
Choose a starting point: the [Kontaktverwaltung-Tutorial](kontakt-tutorial.md) builds a small independent application step by step; the [Person desk quick start](quick-start.md) is the broader NeitzelLib reference. The contact example is part of this Designer checkout and runs without the editor. The Person desk uses NeitzelLib's `fx-example` module to demonstrate direct and computed bindings, converters, nested/repeated Components, a Table, selection, messages and dependency injection.
|
||||
|
||||
| I want to… | Read |
|
||||
| --- | --- |
|
||||
| Build and preview the contact-book starter | [Kontaktverwaltung-Tutorial](kontakt-tutorial.md) |
|
||||
| Run the example and open it in the Designer | [Quick start](quick-start.md) |
|
||||
| Start a JavaFX project and connect it to the Designer | [Projects and configuration](projects.md) |
|
||||
| Understand sample Models, build snapshots and previews | [Preview and build workflow](previews.md) |
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
# JavaFX-Einstieg: Kontaktverwaltung mit NeitzelLib FX
|
||||
|
||||
Dieses Tutorial verwendet das eigenständige Beispiel unter [`examples/contact-book`](../../examples/contact-book/README.md). Es beginnt mit einer lauffähigen JavaFX-Anwendung und zeigt anschließend, wie dieselbe FXML-View mit einem echten NeitzelLib-Binding im IntelliJ-Designer geöffnet und interaktiv ausprobiert wird. Die Kontakt- und Vorschau-Daten bleiben vorerst im Arbeitsspeicher; Telefon-, Adress- und JSON-Funktionen kommen in späteren Abschnitten hinzu.
|
||||
|
||||
## 1. Voraussetzungen und Versionen
|
||||
|
||||
Die überprüfte Ausgangskombination für dieses Beispiel ist:
|
||||
|
||||
| Teil | Version / Rolle |
|
||||
| --- | --- |
|
||||
| JDK für Build und App | JDK 25 |
|
||||
| Maven | 3.9.11 oder neuer |
|
||||
| JavaFX der Anwendung | 27.0.1 |
|
||||
| NeitzelLib FX | `1.0.6-SNAPSHOT`, lokal gebautes Entwicklungsartefakt |
|
||||
| IntelliJ-Plugin | NeitzelFXDesigner `0.1.0-SNAPSHOT`, lokal gebaut |
|
||||
| IntelliJ-Host | SDK `263.7307.200` auf macOS; JavaFX/Scene Builder Kit 26 im Host |
|
||||
|
||||
Die JDK-/JavaFX-Version der Anwendung ist unabhängig vom JavaFX-Toolkit des IntelliJ-Prozesses. Anwendungs- und Vorschau-Code läuft im Zielprozess. Diese Kombination ist eine Entwicklungsbaseline, kein veröffentlichtes Release oder eine Zusage für andere IDE- und Betriebssystemversionen. Die zugehörigen Quellstände und Artefaktgrenzen stehen in der [NeitzelLib-Baseline](../runtime/neitzellib-baseline.md).
|
||||
|
||||
Für den `1.0.6-SNAPSHOT` müssen `fx` und für die Tests auch `fx-test` lokal installiert sein. Folge dazu dem Abschnitt „Rebuild and verify“ in der Baseline; die Workspace-Checkouts enthalten die benötigten Quellen unter `NeitzelLib/` und `NeitzelFXDesigner/`. Falls du dafür ein separates Maven-Repository verwendest, müssen Maven, Gradle und der aus IntelliJ gestartete Maven-Build auf dasselbe Repository zugreifen. Starte IntelliJ dann aus der Shell mit dem dort gesetzten `MAVEN_OPTS`. Das Beispiel kopiert keine Bibliotheksquellen und enthält keinen Designer-Host als Laufzeitabhängigkeit.
|
||||
|
||||
## 2. Die Anwendung separat starten
|
||||
|
||||
Öffne in IntelliJ **den Ordner `examples/contact-book` als eigenes Maven-Projekt**, nicht den Designer-Checkout als übergeordnetes Anwendungsmodul. Das Projekt verwendet den normalen Classpath und benötigt für seinen App-Start weder das Plugin noch `designer-preview-api`.
|
||||
|
||||
Im Beispielordner:
|
||||
|
||||
```sh
|
||||
mvn -version
|
||||
mvn -B -ntp test
|
||||
mvn -B -ntp javafx:run
|
||||
```
|
||||
|
||||
Prüfe, dass `mvn -version` sowohl Maven 3.9.11+ als auch Java 25 meldet. Das Fenster enthält zwei fiktive Kontakte. Wähle einen aus, ändere seinen Namen, füge einen Kontakt hinzu und lösche ihn wieder. Änderungen bleiben nur in diesem Prozess; nach einem Neustart erscheinen die Beispieldaten von vorn.
|
||||
|
||||
## 3. Model, View, ViewModel und Controller
|
||||
|
||||
- `Main` ist der Launcher und startet JavaFX mit `Application.launch`.
|
||||
- `ContactBookApp` erzeugt das Beispieldatenmodell, den NeitzelLib-`ApplicationContext` und die `Scene`. Sie lädt `ContactBook.fxml` durch `ViewLoader`.
|
||||
- `ContactBook` und `Contact` sind gewöhnliche JavaBeans. Sie enthalten keine JavaFX-Properties.
|
||||
- `ContactBook.fxml` und `ContactDetails.fxml` sind die Views: FXML beschreibt die Controls und erklärt Bindings.
|
||||
- NeitzelLib erzeugt zur Laufzeit ein beobachtbares `ViewModel`. Dafür werden keine `ViewModel`-Klassen generiert.
|
||||
- `ContactBookController` behandelt Hinzufügen, Löschen und Auswahl. Beim Wechsel schließt er die bisherige verwaltete Detail-View, bevor er eine neue für das ausgewählte Model lädt.
|
||||
|
||||
Das erste bidirektionale Binding steht in `src/main/resources/de/neitzel/contactbook/view/ContactDetails.fxml`:
|
||||
|
||||
```xml
|
||||
<DirectBinding control="nameField" property="text" path="name" direction="both"/>
|
||||
```
|
||||
|
||||
`both` zeigt den initialen Modellnamen im Textfeld an und schreibt spätere Eingaben sofort über das ViewModel zurück in genau diesen `Contact`. Die Kontaktliste bindet ihre ObservableList ebenfalls direkt an `ContactBook.contacts`; die Auswahl wird vom Controller über das ViewModel gesetzt. Eine direkte JavaBean-Änderung nach dem Laden benachrichtigt NeitzelLib nicht. Ändere Werte daher über ein Binding oder das ViewModel, nicht durch einen stillen Setter am bereits angezeigten Model.
|
||||
|
||||
## 4. Das Projekt mit dem Designer verbinden
|
||||
|
||||
Die Projektkonfiguration ist eingecheckt: `neitzel-fx-designer.json` benennt den Maven-Kontext, die Java-25-Build- und Zielrollen und das optionale Profil `designer-preview`. Sie enthält keine lokalen Rechnerpfade. Das Projekt ignoriert `.neitzel-fx-designer/` und `target/`.
|
||||
|
||||
Das Beispielprojekt wird normal zuerst getestet und gestartet. Für eine IntelliJ-Vorschau müssen zusätzlich die Designer-Artefakte gebaut/installiert sein. Baue die Maven-Module im Designer-Checkout wie im [Quick Start, Abschnitt 2](quick-start.md#2-build-the-project-side-tools-and-development-host) beschrieben. Baue danach das lokale Plugin mit einem JDK 25 und dem passenden IntelliJ SDK:
|
||||
|
||||
```sh
|
||||
export JAVA_HOME=/absolute/path/to/jdk-25
|
||||
export IDEA_HOME=/Applications/YourQualifiedIDE.app/Contents
|
||||
./designer-intellij/gradlew -p designer-intellij --no-daemon \
|
||||
-PideaHome="$IDEA_HOME" test buildPlugin verifyPluginProjectConfiguration
|
||||
```
|
||||
|
||||
Das Plugin-ZIP liegt in `designer-intellij/build/distributions/`. Installiere es in IntelliJ über **Plugins → Install Plugin from Disk** und starte IntelliJ neu. Öffne anschließend **Find Action → Registry**, setze `embed.scene.builder` auf `false` und starte IntelliJ bei Bedarf erneut. Das eingebettete Scene Builder Plugin darf nicht gleichzeitig aktiv sein: beide laden konkurrierende JavaFX-Glass-/Kit-Toolkits in denselben IDE-Prozess. Lass die JavaFX-/FXML-Sprachunterstützung aktiviert. Die [IntelliJ-Anleitung](intellij.md) beschreibt den Host und seine Grenzen ausführlicher.
|
||||
|
||||
Die Pfade zu lokalen JDKs und Worker-JARs gehören nur in ignorierte Laufzeitdateien. Vom Designer-Checkout aus kannst du den projektspezifischen Helfer verwenden:
|
||||
|
||||
```sh
|
||||
python3 scripts/configure-library-example.py \
|
||||
--project /absolute/path/to/NeitzelFXDesigner/examples/contact-book \
|
||||
--target-java-home /absolute/path/to/jdk-25
|
||||
```
|
||||
|
||||
Er schreibt `.neitzel-fx-designer/runtimes.json` und `host.properties` im Beispielprojekt. Der Helfer setzt voraus, dass die Designer-Worker-Artefakte bereits installiert sind und überschreibt vorhandene lokale Einstellungen nicht. `neitzel-fx-designer.json` bleibt dagegen Teil des Projekts und wählt den Kontext `contact-book`.
|
||||
|
||||
## 5. FXML bauen und Daten interaktiv ausprobieren
|
||||
|
||||
1. Öffne `src/main/resources/de/neitzel/contactbook/view/ContactBook.fxml` mit dem **Neitzel Designer**-Editor. Die normale IntelliJ-XML-Ansicht bleibt daneben verfügbar.
|
||||
2. Wähle **Build and Refresh**. Erst dieser Schritt erstellt einen erfolgreichen, isolierten Anwendungssnapshot; ein gewöhnlicher Maven- oder IntelliJ-Build aktiviert die Vorschau nicht.
|
||||
3. Wähle **Kontaktverwaltung · Beispieldaten** im Vorschau-Auswahlfeld, falls es nicht schon vorausgewählt ist. Starte **Interactive preview**. Die Vorschau zeigt die Liste und lädt die Detail-View für den ausgewählten Kontakt.
|
||||
4. Ändere den Namen, wechsle den Kontakt und ändere ihn ebenfalls. Klicke im Designer erneut auf **Interactive preview**, um die Vorschau neu zu starten. Das neue Fenster zeigt wieder `Ada Lovelace` und `Grace Hopper`. Mit **Stop preview** beendest du den Vorschauprozess.
|
||||
|
||||
Die Vorschau und die normale Anwendung rufen dieselbe `ContactBook.fxml` und denselben `ContactBookApp.sample()`-Modellaufbau auf. Der Preview-Provider erstellt bei jedem `open` ein frisches Model und einen frischen Anwendungskontext. Das Schreiben oder erneute Öffnen der FXML speichert nur den View-Aufbau; es speichert nicht die geänderten Kontakte. Zurzeit gibt es absichtlich weder eine Datei noch eine Datenbank.
|
||||
|
||||
Ein Test lädt die echte FXML und prüft das Binding, den Kontaktwechsel und das Abtrennen der vorherigen Detail-View. Das optionale Profil fügt ausschließlich `src/designer/java`, `src/designer/resources` und die test-scoped Preview-API hinzu. Ohne `-Pdesigner-preview` gibt es keine Designer-Klassen im App-Runtime-Classpath.
|
||||
|
||||
## Weiter geht's
|
||||
|
||||
Die nächsten Abschnitte ergänzen Telefonnummern und Adressen als wiederverwendbare Components und zeigen anschließend, wie du Kontakte lokal als JSON speicherst und lädst.
|
||||
@@ -0,0 +1,2 @@
|
||||
.neitzel-fx-designer/
|
||||
target/
|
||||
@@ -0,0 +1,40 @@
|
||||
# Kontaktverwaltung · JavaFX-Einstieg mit NeitzelLib FX
|
||||
|
||||
Ein kleines Maven-Projekt für den Einstieg in JavaFX und MVVM. Die Anwendung verwaltet fiktive Kontakte mit Kontaktliste, Auswahl und editierbarem Namen. Das ausführliche [Tutorial](../../docs/user-guide/kontakt-tutorial.md) führt durch Maven-Import, Model/View/ViewModel/Controller, das erste Binding und die IntelliJ-Vorschau.
|
||||
|
||||
## Bauen und starten
|
||||
|
||||
Voraussetzungen sind `de.neitzel.lib:fx:1.0.6-SNAPSHOT` (für die Tests zusätzlich `fx-test`), JDK 25 und Maven 3.9.11 oder neuer. Der lokale Entwicklungs-Snapshot wird aus dem NeitzelLib-Checkout gebaut; siehe [Baseline und Rebuild](../../docs/runtime/neitzellib-baseline.md). Aus diesem Ordner:
|
||||
|
||||
```sh
|
||||
mvn -version
|
||||
mvn -B -ntp test
|
||||
mvn -B -ntp javafx:run
|
||||
```
|
||||
|
||||
Die normale App benötigt weder NeitzelFXDesigner noch dessen Vorschau-Artefakte. Die Daten werden nur im Arbeitsspeicher gehalten und beim nächsten Start durch frische Beispieldaten ersetzt.
|
||||
|
||||
## Dem Ablauf folgen
|
||||
|
||||
| Datei | Aufgabe |
|
||||
| --- | --- |
|
||||
| `src/main/java/de/neitzel/contactbook/Main.java` | Startet JavaFX über `Application.launch`. |
|
||||
| `ContactBookApp` | Erzeugt das Beispieldatenmodell, `ApplicationContext`, `Scene` und Haupt-View. |
|
||||
| `model/ContactBook`, `model/Contact` | Einfache JavaBeans ohne JavaFX-Properties. |
|
||||
| `view/ContactBook.fxml` | Kontaktliste, Aktionen und Binding der Model-Liste. |
|
||||
| `view/ContactDetails.fxml` | Detail-View mit dem bidirektionalen Namens-Binding. |
|
||||
| `view/ContactBookController` | Synchronisiert Auswahl und Aktionen; schließt die alte Detail-View beim Wechsel. |
|
||||
| `src/test/.../ContactBookLoadsTest` | Prüft die echte FXML, Model-Schreibzugriff und Auswahlwechsel. |
|
||||
| `src/designer/.../ContactBookPreviewProvider` | Optionaler, frischer Vorschauzustand außerhalb des normalen App-Builds. |
|
||||
|
||||
`ContactBookApp.sample()` erstellt `Ada Lovelace` und `Grace Hopper`. Das Beispiel enthält vorerst keine Telefon-/Adressfelder und keine Persistenz.
|
||||
|
||||
## Optionale Designer-Vorschau
|
||||
|
||||
Die Vorschau hängt am Maven-Profil `designer-preview` und der eingecheckten `neitzel-fx-designer.json`. Zuerst müssen die Designer-Worker und die passende lokale Preview-API im NeitzelFXDesigner-Checkout installiert sein. Folge danach dem [Tutorialabschnitt für Plugin und lokale Projektkonfiguration](../../docs/user-guide/kontakt-tutorial.md#4-das-projekt-mit-dem-designer-verbinden). Für den Profil-Build:
|
||||
|
||||
```sh
|
||||
mvn -B -ntp -Pdesigner-preview test
|
||||
```
|
||||
|
||||
Das Profil ergänzt die Vorschau-API mit `test`-Scope und registriert einen Provider mit frischen Models. Es ist nicht erforderlich, um die normale Anwendung zu kompilieren, zu testen oder zu starten.
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"schemaVersion": "1.0",
|
||||
"contexts": {
|
||||
"contact-book": {
|
||||
"applicationModule": ".",
|
||||
"mavenProfiles": ["designer-preview"],
|
||||
"launchMode": "classpath",
|
||||
"buildRuntime": "java25",
|
||||
"targetRuntime": "java25",
|
||||
"buildJava": 25,
|
||||
"targetJava": 25,
|
||||
"preview": {
|
||||
"sourceSet": "test",
|
||||
"provider": "de.neitzel.contactbook.preview.ContactBookPreviewProvider",
|
||||
"defaultExample": "contact-book"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
<?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>
|
||||
|
||||
<groupId>de.neitzel.examples</groupId>
|
||||
<artifactId>contact-book</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.release>25</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
|
||||
<designer.version>0.1.0-SNAPSHOT</designer.version>
|
||||
<javafx.version>27.0.1</javafx.version>
|
||||
<junit.version>6.1.3</junit.version>
|
||||
<neitzellib.version>1.0.6-SNAPSHOT</neitzellib.version>
|
||||
<slf4j.version>2.0.20</slf4j.version>
|
||||
|
||||
<build-helper-maven-plugin.version>3.8.0</build-helper-maven-plugin.version>
|
||||
<javafx-maven-plugin.version>0.0.8</javafx-maven-plugin.version>
|
||||
<maven-compiler-plugin.version>3.16.0</maven-compiler-plugin.version>
|
||||
<maven-surefire-plugin.version>3.6.1</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>de.neitzel.lib</groupId>
|
||||
<artifactId>fx</artifactId>
|
||||
<version>${neitzellib.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-controls</artifactId>
|
||||
<version>${javafx.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-fxml</artifactId>
|
||||
<version>${javafx.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>${slf4j.version}</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>de.neitzel.lib</groupId>
|
||||
<artifactId>fx-test</artifactId>
|
||||
<version>${neitzellib.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<glass.platform>Headless</glass.platform>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.openjfx</groupId>
|
||||
<artifactId>javafx-maven-plugin</artifactId>
|
||||
<version>${javafx-maven-plugin.version}</version>
|
||||
<configuration>
|
||||
<mainClass>de.neitzel.contactbook.Main</mainClass>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>designer-preview</id>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>de.neitzel.fxdesigner</groupId>
|
||||
<artifactId>designer-preview-api</artifactId>
|
||||
<version>${designer.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>build-helper-maven-plugin</artifactId>
|
||||
<version>${build-helper-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>designer-preview-sources</id>
|
||||
<phase>generate-test-sources</phase>
|
||||
<goals>
|
||||
<goal>add-test-source</goal>
|
||||
<goal>add-test-resource</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<sources>
|
||||
<source>src/designer/java</source>
|
||||
</sources>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/designer/resources</directory>
|
||||
</resource>
|
||||
</resources>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
</project>
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package de.neitzel.contactbook.preview;
|
||||
|
||||
import de.neitzel.contactbook.ContactBookApp;
|
||||
import de.neitzel.contactbook.model.ContactBook;
|
||||
import de.neitzel.fxdesigner.preview.PreviewProvider;
|
||||
import de.neitzel.fxdesigner.preview.PreviewSession;
|
||||
import de.neitzel.injection.ApplicationContext;
|
||||
|
||||
public final class ContactBookPreviewProvider implements PreviewProvider<ContactBook, ApplicationContext> {
|
||||
|
||||
@Override
|
||||
public Class<ContactBook> modelType() {
|
||||
return ContactBook.class;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PreviewSession<ContactBook, ApplicationContext> open(String exampleId) {
|
||||
if (!"contact-book".equals(exampleId)) {
|
||||
throw new IllegalArgumentException("Unbekanntes Kontaktbeispiel: " + exampleId);
|
||||
}
|
||||
return new ContactBookSession(ContactBookApp.sample(), new ApplicationContext(ContactBookApp.class));
|
||||
}
|
||||
|
||||
private record ContactBookSession(ContactBook model, ApplicationContext context)
|
||||
implements PreviewSession<ContactBook, ApplicationContext> {
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package de.neitzel.contactbook.preview;
|
||||
|
||||
import de.neitzel.contactbook.view.ContactBookController;
|
||||
import de.neitzel.fx.test.FxFixture;
|
||||
import de.neitzel.fx.test.FxTest;
|
||||
import de.neitzel.fx.view.LoadedView;
|
||||
import javafx.scene.control.TextField;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
|
||||
@FxTest
|
||||
class ContactBookPreviewProviderTest {
|
||||
|
||||
@Test
|
||||
void everyPreviewStartsWithFreshContactModels(FxFixture fx) throws Exception {
|
||||
ContactBookPreviewProvider provider = new ContactBookPreviewProvider();
|
||||
var first = provider.open("contact-book");
|
||||
var second = provider.open("contact-book");
|
||||
LoadedView view = fx.load(ContactBookController.class.getResource("ContactBook.fxml"),
|
||||
first.model(), first.context());
|
||||
|
||||
assertNotSame(first.model(), second.model());
|
||||
assertNotSame(first.model().getContacts().getFirst(), second.model().getContacts().getFirst());
|
||||
assertNotSame(first.context(), second.context());
|
||||
fx.await("preview contact details", () -> hasNameField(fx, view));
|
||||
fx.run(() -> ((TextField) view.getRoot().lookup("#nameField")).setText("Preview-only name"));
|
||||
assertEquals("Preview-only name", first.model().getSelectedContact().getName());
|
||||
assertEquals("Ada Lovelace", second.model().getSelectedContact().getName());
|
||||
|
||||
first.close();
|
||||
second.close();
|
||||
}
|
||||
|
||||
private static boolean hasNameField(FxFixture fx, LoadedView view) {
|
||||
try {
|
||||
return fx.call(() -> view.getRoot().lookup("#nameField") instanceof TextField);
|
||||
} catch (Exception failure) {
|
||||
throw new IllegalStateException(failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
format=1
|
||||
count=1
|
||||
example.0.id=contact-book
|
||||
example.0.label=Kontaktverwaltung · Beispieldaten
|
||||
example.0.modelType=de.neitzel.contactbook.model.ContactBook
|
||||
example.0.providerClass=de.neitzel.contactbook.preview.ContactBookPreviewProvider
|
||||
example.0.viewResource=de/neitzel/contactbook/view/ContactBook.fxml
|
||||
example.0.componentPackage=de.neitzel.contactbook.view
|
||||
@@ -0,0 +1,42 @@
|
||||
package de.neitzel.contactbook;
|
||||
|
||||
import de.neitzel.contactbook.model.Contact;
|
||||
import de.neitzel.contactbook.model.ContactBook;
|
||||
import de.neitzel.contactbook.view.ContactBookController;
|
||||
import de.neitzel.fx.view.LoadedView;
|
||||
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 java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Config(basePackage = "de.neitzel.contactbook")
|
||||
public class ContactBookApp extends Application {
|
||||
|
||||
public static ContactBook sample() {
|
||||
ContactBook book = new ContactBook();
|
||||
Contact ada = new Contact("Ada Lovelace");
|
||||
book.setContacts(new ArrayList<>(List.of(ada, new Contact("Grace Hopper"))));
|
||||
book.setSelectedContact(ada);
|
||||
return book;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start(Stage stage) {
|
||||
ApplicationContext services = new ApplicationContext(ContactBookApp.class);
|
||||
ViewModelContext models = new ViewModelContext();
|
||||
LoadedView view = ViewLoader.load(
|
||||
ContactBookController.class.getResource("ContactBook.fxml"), sample(), services, models);
|
||||
stage.setTitle("Kontaktverwaltung · NeitzelLib FX");
|
||||
stage.setMinWidth(680);
|
||||
stage.setMinHeight(420);
|
||||
stage.setScene(new Scene(view.getRoot()));
|
||||
stage.setOnCloseRequest(event -> models.close());
|
||||
stage.show();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package de.neitzel.contactbook;
|
||||
|
||||
import javafx.application.Application;
|
||||
|
||||
public final class Main {
|
||||
|
||||
private Main() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Application.launch(ContactBookApp.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package de.neitzel.contactbook.model;
|
||||
|
||||
public class Contact {
|
||||
|
||||
private String name = "";
|
||||
|
||||
public Contact() {
|
||||
}
|
||||
|
||||
public Contact(String name) {
|
||||
setName(name);
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name == null ? "" : name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package de.neitzel.contactbook.model;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public class ContactBook {
|
||||
|
||||
private List<Contact> contacts = new ArrayList<>();
|
||||
private Contact selectedContact;
|
||||
|
||||
public List<Contact> getContacts() {
|
||||
return contacts;
|
||||
}
|
||||
|
||||
public void setContacts(List<Contact> contacts) {
|
||||
this.contacts = Objects.requireNonNull(contacts, "contacts");
|
||||
}
|
||||
|
||||
public Contact getSelectedContact() {
|
||||
return selectedContact;
|
||||
}
|
||||
|
||||
public void setSelectedContact(Contact selectedContact) {
|
||||
this.selectedContact = selectedContact;
|
||||
}
|
||||
}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
package de.neitzel.contactbook.view;
|
||||
|
||||
import de.neitzel.contactbook.ContactBookApp;
|
||||
import de.neitzel.contactbook.model.Contact;
|
||||
import de.neitzel.fx.view.HasViewModel;
|
||||
import de.neitzel.fx.view.LoadedView;
|
||||
import de.neitzel.fx.view.ViewLoader;
|
||||
import de.neitzel.fx.view.ViewModel;
|
||||
import de.neitzel.fx.view.ViewModelContext;
|
||||
import de.neitzel.injection.ApplicationContext;
|
||||
import jakarta.inject.Singleton;
|
||||
import javafx.application.Platform;
|
||||
import javafx.beans.property.Property;
|
||||
import javafx.beans.value.ChangeListener;
|
||||
import javafx.collections.ObservableList;
|
||||
import javafx.fxml.FXML;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.Label;
|
||||
import javafx.scene.control.ListCell;
|
||||
import javafx.scene.control.ListView;
|
||||
import javafx.scene.layout.StackPane;
|
||||
|
||||
@Singleton
|
||||
public class ContactBookController implements HasViewModel, AutoCloseable {
|
||||
|
||||
@FXML
|
||||
private ListView<Contact> contactList;
|
||||
|
||||
@FXML
|
||||
private Button deleteContactButton;
|
||||
|
||||
@FXML
|
||||
private StackPane detailContainer;
|
||||
|
||||
@FXML
|
||||
private Label emptyState;
|
||||
|
||||
private ViewModel viewModel;
|
||||
private Property<Object> selectedContactAttribute;
|
||||
private Contact currentContact;
|
||||
private LoadedView detailView;
|
||||
private ViewModelContext detailModels;
|
||||
private Property<Object> detailNameAttribute;
|
||||
private ChangeListener<Object> detailNameListener;
|
||||
|
||||
@FXML
|
||||
public void initialize() {
|
||||
contactList.setCellFactory(list -> new ListCell<>() {
|
||||
@Override
|
||||
protected void updateItem(Contact contact, boolean empty) {
|
||||
super.updateItem(contact, empty);
|
||||
setText(empty || contact == null ? null : displayName(contact));
|
||||
}
|
||||
});
|
||||
deleteContactButton.setDisable(true);
|
||||
contactList.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, selected) -> {
|
||||
deleteContactButton.setDisable(selected == null);
|
||||
if (selectedContactAttribute != null) {
|
||||
selectedContactAttribute.setValue(selected);
|
||||
}
|
||||
showDetails(selected);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setViewModel(ViewModel viewModel) {
|
||||
this.viewModel = viewModel;
|
||||
selectedContactAttribute = attribute("selectedContact");
|
||||
Platform.runLater(this::selectInitialContact);
|
||||
}
|
||||
|
||||
@FXML
|
||||
public void addContact() {
|
||||
Contact contact = new Contact("Neuer Kontakt");
|
||||
contacts().add(contact);
|
||||
contactList.getSelectionModel().select(contact);
|
||||
}
|
||||
|
||||
@FXML
|
||||
public void deleteContact() {
|
||||
Contact selected = contactList.getSelectionModel().getSelectedItem();
|
||||
if (selected == null) {
|
||||
return;
|
||||
}
|
||||
int previousIndex = contactList.getSelectionModel().getSelectedIndex();
|
||||
contacts().remove(selected);
|
||||
if (contactList.getSelectionModel().getSelectedItem() == selected) {
|
||||
if (contacts().isEmpty()) {
|
||||
contactList.getSelectionModel().clearSelection();
|
||||
} else {
|
||||
contactList.getSelectionModel().select(Math.min(Math.max(previousIndex, 0), contacts().size() - 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
closeDetail();
|
||||
}
|
||||
|
||||
private void selectInitialContact() {
|
||||
if (viewModel == null || contactList.getItems().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Contact selected = contactList.getSelectionModel().getSelectedItem();
|
||||
if (selected == null || !contactList.getItems().contains(selected)) {
|
||||
selected = contactList.getItems().getFirst();
|
||||
}
|
||||
contactList.getSelectionModel().select(selected);
|
||||
}
|
||||
|
||||
private void showDetails(Contact selected) {
|
||||
if (selected == currentContact && (selected == null || detailView != null)) {
|
||||
return;
|
||||
}
|
||||
closeDetail();
|
||||
currentContact = selected;
|
||||
if (selected == null) {
|
||||
detailContainer.getChildren().setAll(emptyState);
|
||||
return;
|
||||
}
|
||||
|
||||
ViewModelContext models = new ViewModelContext();
|
||||
try {
|
||||
LoadedView loaded = ViewLoader.load(
|
||||
ContactBookController.class.getResource("ContactDetails.fxml"),
|
||||
selected,
|
||||
new ApplicationContext(ContactBookApp.class),
|
||||
models);
|
||||
detailModels = models;
|
||||
detailView = loaded;
|
||||
detailContainer.getChildren().setAll(loaded.getRoot());
|
||||
observeName(loaded);
|
||||
} catch (RuntimeException | Error failure) {
|
||||
models.close();
|
||||
currentContact = null;
|
||||
detailContainer.getChildren().setAll(emptyState);
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private void observeName(LoadedView loaded) {
|
||||
detailNameAttribute = attribute(loaded.getViewModel(), "name");
|
||||
detailNameListener = (observable, oldValue, newValue) -> contactList.refresh();
|
||||
detailNameAttribute.addListener(detailNameListener);
|
||||
}
|
||||
|
||||
private void closeDetail() {
|
||||
if (detailNameAttribute != null && detailNameListener != null) {
|
||||
detailNameAttribute.removeListener(detailNameListener);
|
||||
}
|
||||
LoadedView oldView = detailView;
|
||||
ViewModelContext oldModels = detailModels;
|
||||
detailNameAttribute = null;
|
||||
detailNameListener = null;
|
||||
detailView = null;
|
||||
detailModels = null;
|
||||
if (oldView != null) {
|
||||
oldView.close();
|
||||
}
|
||||
if (oldModels != null) {
|
||||
oldModels.close();
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private Property<Object> attribute(String name) {
|
||||
return (Property<Object>) viewModel.property(name);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Property<Object> attribute(ViewModel viewModel, String name) {
|
||||
return (Property<Object>) viewModel.property(name);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private ObservableList<Contact> contacts() {
|
||||
return (ObservableList<Contact>) viewModel.property("contacts").getValue();
|
||||
}
|
||||
|
||||
private static String displayName(Contact contact) {
|
||||
return contact.getName().isBlank() ? "(Ohne Namen)" : contact.getName();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<?neitzel-model de.neitzel.contactbook.model.ContactBook?>
|
||||
|
||||
<?import de.neitzel.fx.view.BindingList?>
|
||||
<?import de.neitzel.fx.view.DirectBinding?>
|
||||
<?import javafx.geometry.Insets?>
|
||||
<?import javafx.scene.control.Button?>
|
||||
<?import javafx.scene.control.Label?>
|
||||
<?import javafx.scene.control.ListView?>
|
||||
<?import javafx.scene.layout.BorderPane?>
|
||||
<?import javafx.scene.layout.HBox?>
|
||||
<?import javafx.scene.layout.StackPane?>
|
||||
<?import javafx.scene.layout.VBox?>
|
||||
|
||||
<BorderPane xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml/1"
|
||||
fx:controller="de.neitzel.contactbook.view.ContactBookController"
|
||||
prefWidth="860" prefHeight="560">
|
||||
<fx:define>
|
||||
<BindingList>
|
||||
<DirectBinding control="contactList" property="items" path="contacts" direction="view"/>
|
||||
</BindingList>
|
||||
</fx:define>
|
||||
<top>
|
||||
<VBox spacing="8">
|
||||
<padding>
|
||||
<Insets top="16" right="18" bottom="12" left="18"/>
|
||||
</padding>
|
||||
<Label text="Kontaktverwaltung" style="-fx-font-size: 22px; -fx-font-weight: bold;"/>
|
||||
<HBox spacing="8">
|
||||
<Button id="addContactButton" text="Kontakt hinzufügen" onAction="#addContact"/>
|
||||
<Button fx:id="deleteContactButton" id="deleteContactButton" text="Ausgewählten Kontakt löschen"
|
||||
onAction="#deleteContact"/>
|
||||
</HBox>
|
||||
</VBox>
|
||||
</top>
|
||||
<left>
|
||||
<VBox spacing="8" prefWidth="260">
|
||||
<padding>
|
||||
<Insets top="12" right="12" bottom="16" left="18"/>
|
||||
</padding>
|
||||
<Label text="Kontakte" style="-fx-font-size: 15px; -fx-font-weight: bold;"/>
|
||||
<ListView fx:id="contactList" id="contactList" VBox.vgrow="ALWAYS"/>
|
||||
</VBox>
|
||||
</left>
|
||||
<center>
|
||||
<StackPane fx:id="detailContainer" id="detailContainer">
|
||||
<padding>
|
||||
<Insets top="12" right="18" bottom="16" left="12"/>
|
||||
</padding>
|
||||
<Label fx:id="emptyState" id="emptyState" text="Wähle einen Kontakt aus, um die Details zu bearbeiten."/>
|
||||
</StackPane>
|
||||
</center>
|
||||
</BorderPane>
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<?neitzel-model de.neitzel.contactbook.model.Contact?>
|
||||
|
||||
<?import de.neitzel.fx.view.BindingList?>
|
||||
<?import de.neitzel.fx.view.DirectBinding?>
|
||||
<?import javafx.geometry.Insets?>
|
||||
<?import javafx.scene.control.Label?>
|
||||
<?import javafx.scene.control.TextField?>
|
||||
<?import javafx.scene.layout.VBox?>
|
||||
|
||||
<VBox xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml/1" spacing="10"
|
||||
prefWidth="480" prefHeight="220" style="-fx-background-color: white;">
|
||||
<fx:define>
|
||||
<BindingList>
|
||||
<DirectBinding control="nameField" property="text" path="name" direction="both"/>
|
||||
</BindingList>
|
||||
</fx:define>
|
||||
<padding>
|
||||
<Insets top="18" right="18" bottom="18" left="18"/>
|
||||
</padding>
|
||||
<Label text="Kontaktdetails" style="-fx-font-size: 18px; -fx-font-weight: bold;"/>
|
||||
<Label text="Name"/>
|
||||
<TextField fx:id="nameField" id="nameField" promptText="Name des Kontakts"/>
|
||||
<Label text="Der Name wird direkt im ausgewählten Model gespeichert." wrapText="true"/>
|
||||
</VBox>
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package de.neitzel.contactbook.view;
|
||||
|
||||
import de.neitzel.contactbook.ContactBookApp;
|
||||
import de.neitzel.contactbook.model.Contact;
|
||||
import de.neitzel.contactbook.model.ContactBook;
|
||||
import de.neitzel.fx.test.FxFixture;
|
||||
import de.neitzel.fx.test.FxTest;
|
||||
import de.neitzel.fx.view.LoadedView;
|
||||
import de.neitzel.injection.ApplicationContext;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.ListView;
|
||||
import javafx.scene.control.TextField;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@FxTest
|
||||
class ContactBookLoadsTest {
|
||||
|
||||
@Test
|
||||
void realViewsBindNamesAndDetachThePreviousSelection(FxFixture fx) throws Exception {
|
||||
ContactBook book = ContactBookApp.sample();
|
||||
LoadedView view = load(fx, book);
|
||||
Contact ada = book.getContacts().getFirst();
|
||||
Contact grace = book.getContacts().get(1);
|
||||
|
||||
fx.await("initial contact details", () -> hasNameField(fx, view));
|
||||
fx.run(() -> {
|
||||
ListView<?> list = list(view);
|
||||
assertEquals(2, list.getItems().size());
|
||||
assertSame(ada, list.getSelectionModel().getSelectedItem());
|
||||
assertEquals("Ada Lovelace", nameField(view).getText());
|
||||
nameField(view).setText("Ada Byron");
|
||||
assertEquals("Ada Byron", ada.getName());
|
||||
|
||||
list.getSelectionModel().select(1);
|
||||
assertEquals(grace, book.getSelectedContact());
|
||||
assertEquals("Grace Hopper", nameField(view).getText());
|
||||
nameField(view).setText("Grace Murray Hopper");
|
||||
assertEquals("Grace Murray Hopper", grace.getName());
|
||||
assertEquals("Ada Byron", ada.getName());
|
||||
|
||||
TextField removedField = nameField(view);
|
||||
list.getSelectionModel().clearSelection();
|
||||
assertNull(book.getSelectedContact());
|
||||
assertTrue(view.getRoot().lookup("#emptyState").isVisible());
|
||||
assertTrue(view.getRoot().lookup("#nameField") == null);
|
||||
removedField.setText("Detached edit");
|
||||
assertEquals("Grace Murray Hopper", grace.getName());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void usersCanAddSelectRenameAndDeleteContacts(FxFixture fx) throws Exception {
|
||||
ContactBook book = ContactBookApp.sample();
|
||||
LoadedView view = load(fx, book);
|
||||
fx.await("initial contact details", () -> hasNameField(fx, view));
|
||||
|
||||
fx.run(() -> addButton(view).fire());
|
||||
assertEquals(3, book.getContacts().size());
|
||||
Contact added = book.getSelectedContact();
|
||||
assertTrue(book.getContacts().contains(added));
|
||||
fx.run(() -> nameField(view).setText("New contact"));
|
||||
assertEquals("New contact", added.getName());
|
||||
|
||||
fx.run(() -> deleteButton(view).fire());
|
||||
assertFalse(book.getContacts().contains(added));
|
||||
assertEquals(2, book.getContacts().size());
|
||||
assertTrue(book.getSelectedContact() == null || book.getContacts().contains(book.getSelectedContact()));
|
||||
assertEquals(book.getSelectedContact() == null, deleteButton(view).isDisabled());
|
||||
|
||||
fx.run(() -> list(view).getSelectionModel().clearSelection());
|
||||
fx.run(() -> deleteButton(view).fire());
|
||||
assertEquals(2, book.getContacts().size());
|
||||
assertNull(book.getSelectedContact());
|
||||
assertTrue(deleteButton(view).isDisabled());
|
||||
}
|
||||
|
||||
private static LoadedView load(FxFixture fx, ContactBook book) throws Exception {
|
||||
return fx.load(ContactBookController.class.getResource("ContactBook.fxml"),
|
||||
book, new ApplicationContext(ContactBookApp.class));
|
||||
}
|
||||
|
||||
private static boolean hasNameField(FxFixture fx, LoadedView view) {
|
||||
try {
|
||||
return fx.call(() -> view.getRoot().lookup("#nameField") instanceof TextField);
|
||||
} catch (Exception failure) {
|
||||
throw new IllegalStateException(failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static ListView<?> list(LoadedView view) {
|
||||
return (ListView<?>) view.getRoot().lookup("#contactList");
|
||||
}
|
||||
|
||||
private static TextField nameField(LoadedView view) {
|
||||
return (TextField) view.getRoot().lookup("#nameField");
|
||||
}
|
||||
|
||||
private static Button addButton(LoadedView view) {
|
||||
return (Button) view.getRoot().lookup("#addContactButton");
|
||||
}
|
||||
|
||||
private static Button deleteButton(LoadedView view) {
|
||||
return (Button) view.getRoot().lookup("#deleteContactButton");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user