1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 package it.tidalwave.ui.javafx;
27
28 import jakarta.annotation.Nonnull;
29 import java.io.IOException;
30 import java.net.URL;
31 import javafx.fxml.FXMLLoader;
32 import javafx.scene.Node;
33 import javafx.application.Platform;
34 import it.tidalwave.util.ReflectionUtils;
35 import lombok.Getter;
36 import lombok.RequiredArgsConstructor;
37 import lombok.extern.slf4j.Slf4j;
38 import static lombok.AccessLevel.PRIVATE;
39
40
41
42
43
44
45 @RequiredArgsConstructor(access = PRIVATE) @Getter @Slf4j
46 public final class NodeAndDelegate<T>
47 {
48 @Nonnull
49 private final Node node;
50
51 @Nonnull
52 private final T delegate;
53
54 @Nonnull
55 public static <T> NodeAndDelegate<T> load (@Nonnull final Class<T> clazz, @Nonnull final String resource)
56 throws IOException
57 {
58 log.debug("NodeAndDelegate({}, {})", clazz, resource);
59 assert Platform.isFxApplicationThread() : "Not in JavaFX UI Thread";
60 final var loader = new FXMLLoader(clazz.getResource(resource), null, null,
61 type -> ReflectionUtils.instantiateWithDependencies(type, JavaFXSafeProxyCreator.BEANS));
62 try
63 {
64 final Node node = loader.load();
65 final T jfxController = loader.getController();
66 ReflectionUtils.injectDependencies(jfxController, JavaFXSafeProxyCreator.BEANS);
67 final var interfaces = jfxController.getClass().getInterfaces();
68
69 if (interfaces.length == 0)
70 {
71 log.warn("{} has no interface: not creating safe proxy", jfxController.getClass());
72 log.debug(">>>> load({}, {}) completed", clazz, resource);
73 return new NodeAndDelegate<>(node, jfxController);
74 }
75 else
76 {
77 final var safeDelegate = JavaFXSafeProxyCreator.createSafeProxy(jfxController, interfaces);
78 log.debug(">>>> load({}, {}) completed", clazz, resource);
79 return new NodeAndDelegate<>(node, safeDelegate);
80 }
81 }
82 catch (IllegalStateException e)
83 {
84 final var message = String.format("ERROR: Cannot find resource: %s/%s", clazz.getPackageName().replace('.','/'), resource);
85 log.error("ERROR: Cannot find resource: {}", message);
86 throw new IllegalStateException(message);
87 }
88 }
89 }