ThemeManager
A centralized controller for application themes. A theme is a named set of stylesheet URLs. Register your themes once, choose an active one, and let the manager apply it to any number of scenes — managed scenes re-style automatically when the active theme changes, enabling live theme switching without leaking memory. Un controlador centralizado para los temas de la aplicación. Un tema es un conjunto con nombre de URLs de hojas de estilo. Registra tus temas una vez, elige uno activo y deja que el manager lo aplique a cualquier número de escenas — las escenas gestionadas se reestilizan automáticamente cuando cambia el tema activo, habilitando el cambio de tema en vivo sin fugas de memoria.
Overview & key conceptsVisión general y conceptos clave
- Surgical stylesheet handling. Applying a theme removes the URLs of all known themes from a scene before adding the active theme's URLs — so your app's own, non-theme stylesheets are never disturbed.Manejo quirúrgico de hojas de estilo. Aplicar un tema elimina las URLs de todos los temas conocidos de una escena antes de añadir las URLs del tema activo — así las hojas de estilo propias de tu app (no temáticas) nunca se ven afectadas.
- Weak scene tracking. Managed scenes are held with weak references (a
WeakHashMap-backed set), so managing a scene never prevents it from being garbage-collected.Rastreo débil de escenas. Las escenas gestionadas se sostienen con referencias débiles (un conjunto respaldado porWeakHashMap), así que gestionar una escena nunca impide que sea recolectada por el GC. - Decoupled from navigation. It deliberately does not depend on
FlowController; bridge the two withasApplier().Desacoplado de la navegación. Deliberadamente no depende deFlowController; conecta ambos conasApplier(). - Thread-safe. The registry is a
ConcurrentHashMap; scene mutations are marshalled onto the FX thread when needed.Thread-safe. El registro es unConcurrentHashMap; las mutaciones de escena se redirigen al hilo de FX cuando es necesario.
Quick startInicio rápido
ThemeManager themes = ThemeManager.getInstance();
themes.registerTheme("dark", "/app/css/dark.css");
themes.registerTheme("light", "/app/css/light.css");
themes.setActiveTheme("dark");
// Let every scene FlowController builds be themed automatically:
FlowController.getInstance().setThemeApplier(themes.asApplier());
// Flip the theme at runtime — all managed scenes update instantly:
themes.setActiveTheme("light");
Theme registryRegistro de temas
Registers (or replaces) a theme. The name must be non-blank; the URL list and its entries must be non-null.Registra (o reemplaza) un tema. El nombre no puede estar en blanco; la lista de URLs y sus entradas no pueden ser null.
Removes a theme. If it was active, the active selection is cleared.Elimina un tema. Si estaba activo, la selección activa se limpia.
Existence check and an unmodifiable snapshot of registered names.Comprobación de existencia y una instantánea no modificable de los nombres registrados.
Active themeTema activo
Activates a registered theme and immediately re-applies it to every managed scene. Throws IllegalArgumentException if the name is null/blank or not registered.Activa un tema registrado y lo reaplica de inmediato a cada escena gestionada. Lanza IllegalArgumentException si el nombre es null/en blanco o no está registrado.
The active name (or null), and a way to clear it — which strips theme stylesheets from managed scenes, returning them to an unstyled state.El nombre activo (o null), y una forma de limpiarlo — que quita las hojas de estilo de tema de las escenas gestionadas, devolviéndolas a un estado sin estilo.
Scene applicationAplicación a escenas
| MethodMétodo | BehaviourComportamiento |
|---|---|
applyTheme(scene) | Applies the active theme once, without tracking the scene for future updates.Aplica el tema activo una vez, sin rastrear la escena para futuras actualizaciones. |
manage(scene) | Applies now and tracks (weakly) for automatic re-theming on every change.Aplica ahora y rastrea (débilmente) para reaplicar el tema automáticamente en cada cambio. |
forget(scene) | Stops tracking a scene; its current stylesheets are left as-is.Deja de rastrear una escena; sus hojas de estilo actuales se mantienen como están. |
asApplier() | Returns a Consumer<Scene> that calls manage — ready for FlowController.setThemeApplier(...).Devuelve un Consumer<Scene> que llama a manage — listo para FlowController.setThemeApplier(...). |
asApplier() is the intended integration point: pass it to FlowController (directly or via an initialize overload) and every scene the controller creates is tracked and themed — so a single setActiveTheme call restyles the entire app.asApplier() es el punto de integración previsto: pásalo a FlowController (directamente o vía una sobrecarga de initialize) y cada escena que cree el controlador queda rastreada y con tema — así una sola llamada a setActiveTheme reestiliza toda la app.
Recommendations & pitfallsRecomendaciones y trampas
Do register all themes at startup, then switch freely — switching is instant across every managed scene.Registra todos los temas al inicio y luego cambia libremente — el cambio es instantáneo en cada escena gestionada.
Do use manage (not applyTheme) for any scene that should follow runtime theme changes.Usa manage (no applyTheme) para cualquier escena que deba seguir los cambios de tema en tiempo de ejecución.
Switching themes removes the URLs of registered themes before adding the active set. A stylesheet you add to a scene by hand (not part of any registered theme) is preserved — but also won't be swapped out. Keep theme stylesheets inside registered themes if you want them managed.Cambiar de tema elimina las URLs de los temas registrados antes de añadir el conjunto activo. Una hoja de estilo que añadas a mano a una escena (que no forme parte de ningún tema registrado) se conserva — pero tampoco se intercambiará. Mantén las hojas de estilo de tema dentro de temas registrados si quieres que se gestionen.