io.github.dinamo541.corefx.navigation

StageManager

Singleton final thread-safe JavaFX

A named registry of Stages plus a uniform, defensive API for their whole life: show / hide / close, window state (maximize, iconify, full-screen, always-on-top, opacity), geometry (size, position, centering, fitting to a screen), icons, and dragging of undecorated windows. Un registro con nombre de Stages más una API uniforme y defensiva para toda su vida: mostrar / ocultar / cerrar, estado de ventana (maximizar, minimizar, pantalla completa, siempre al frente, opacidad), geometría (tamaño, posición, centrado, ajuste a una pantalla), iconos y arrastre de ventanas sin decoración.

OverviewVisión general

Where FlowController concentrates on loading views and swapping scene content, StageManager concentrates on the windows themselves. Register a stage under a key once and address it from anywhere — no need to thread Stage references through your controllers. Mientras FlowController se concentra en cargar vistas e intercambiar el contenido de las escenas, StageManager se concentra en las ventanas en sí. Registra un stage bajo una clave una vez y diríjete a él desde cualquier lugar — sin tener que pasar referencias de Stage por tus controladores.

🧵
Thread-safe by design — the standout featureThread-safe por diseño — la característica estrella

Every UI-mutating method routes through runOnFxThread(...): it runs immediately if you're already on the JavaFX Application Thread, otherwise it defers via Platform.runLater. So you can call StageManager from a background worker without reasoning about threading yourself.Cada método que muta la UI pasa por runOnFxThread(...): se ejecuta de inmediato si ya estás en el JavaFX Application Thread, y si no, lo difiere vía Platform.runLater. Así puedes llamar a StageManager desde un worker en segundo plano sin razonar tú mismo sobre los hilos.

Quick startInicio rápido

StageManager stages = StageManager.getInstance();

Stage report = new Stage();
stages.register("report", report);   // name it once

stages.show("report");               // address it by name anywhere
stages.centerOnCurrentScreen(report);
stages.setAlwaysOnTop(report, true);

// On shutdown:
stages.closeAll();

RegistryRegistro

MethodMétodoReturns / behaviourDevuelve / comportamiento
register(key, stage)Registers (replacing any prior). Returns the previous stage or null. Rejects null/blank key and null stage.Registra (reemplazando cualquier anterior). Devuelve el stage previo o null. Rechaza clave null/en blanco y stage null.
unregister(key)Removes from the registry (does not close it). Returns the removed stage or null.Elimina del registro (no lo cierra). Devuelve el stage eliminado o null.
getStage(key)The stage or null — never throws for a missing key.El stage o null — nunca lanza excepción ante una clave inexistente.
hasStage(key)Whether a stage is registered.Si hay un stage registrado.
getKeys()An unmodifiable snapshot of the keys.Una instantánea no modificable de las claves.
clear()Empties the registry without closing the stages.Vacía el registro sin cerrar los stages.
🔑
Key-addressed operations fail loudlyLas operaciones por clave fallan de forma visible

The lifecycle/by-key methods (show(key), close(key), …) throw IllegalArgumentException when nothing is registered under that key — surfacing the mistake instead of silently doing nothing. Plain lookups (getStage, hasStage) never throw.Los métodos de ciclo de vida/por clave (show(key), close(key), …) lanzan IllegalArgumentException cuando no hay nada registrado bajo esa clave — exponiendo el error en vez de no hacer nada en silencio. Las búsquedas simples (getStage, hasStage) nunca lanzan.

LifecycleCiclo de vida

MethodMétodoBehaviourComportamiento
show(stage) / show(key)Shows (if hidden) and brings to front.Muestra (si está oculto) y trae al frente.
hide(stage) / hide(key)Hides without closing.Oculta sin cerrar.
close(stage)Closes; leaves the registry untouched.Cierra; deja el registro intacto.
close(key)Closes and unregisters in one step.Cierra y desregistra en un solo paso.
closeAll()Closes every registered stage and clears the registry.Cierra todos los stages registrados y vacía el registro.
hideAll()Hides all without closing or clearing.Oculta todos sin cerrarlos ni vaciar el registro.
bringToFront(stage)Shows if needed, then raises to the top of the stack.Muestra si hace falta y luego lo eleva a la cima de la pila.

Window stateEstado de la ventana

MethodMétodoNotesNotas
setMaximized(stage, bool) · toggleMaximized(stage)Maximize / restore.Maximizar / restaurar.
setIconified(stage, bool)Minimize / restore.Minimizar / restaurar.
setFullScreen(stage, bool) · toggleFullScreen(stage)Full-screen control.Control de pantalla completa.
setAlwaysOnTop(stage, bool)Keep above other windows.Mantener por encima de otras ventanas.
setResizable(stage, bool)Allow / forbid user resizing.Permitir / prohibir el redimensionado por el usuario.
setOpacity(stage, double)Clamped to [0.0, 1.0]; NaN1.0, so bad input never yields an invalid window.Acotado a [0.0, 1.0]; NaN1.0, así una entrada mala nunca produce una ventana inválida.
setTitle(stage, String)A null title is normalized to "".Un título null se normaliza a "".

GeometryGeometría

MethodMétodoNotesNotas
setSize / setMinSize / setMaxSize (stage, w, h)Dimensions must be finite and non-negative, else IllegalArgumentException.Las dimensiones deben ser finitas y no negativas, de lo contrario IllegalArgumentException.
setPosition(stage, x, y)Negative coords allowed (valid on multi-monitor); must be finite.Se permiten coordenadas negativas (válidas en multimonitor); deben ser finitas.
centerOnScreen(stage)Platform centering.Centrado de la plataforma.
centerOnCurrentScreen(stage)Centers within the screen that currently holds most of the window — better on multi-monitor.Centra dentro de la pantalla que actualmente contiene la mayor parte de la ventana — mejor en multimonitor.
fitToScreen(stage)Fills the current screen's visual bounds (excluding taskbar) without entering OS maximized/full-screen mode.Llena los límites visuales de la pantalla actual (excluyendo la barra de tareas) sin entrar al modo maximizado/pantalla completa del SO.

Icons & draggingIconos y arrastre

void setIcon(Stage, Image)  ·  void addIcon(Stage, Image)

setIcon replaces all icons with one; addIcon appends. Both reject null arguments.setIcon reemplaza todos los iconos por uno; addIcon añade. Ambos rechazan argumentos null.

void makeDraggable(Stage stage, Node handle)

Makes an undecorated window draggable by pressing on handle (typically a custom title bar). It preserves the cursor-to-origin offset so the window follows the pointer without jumping. Re-registering replaces prior handlers.Hace que una ventana sin decoración se pueda arrastrar pulsando sobre handle (típicamente una barra de título personalizada). Preserva el desplazamiento cursor-a-origen para que la ventana siga al puntero sin saltos. Re-registrar reemplaza los manejadores previos.

void removeDraggable(Node handle)

Removes the drag handlers previously installed on handle.Elimina los manejadores de arrastre instalados previamente en handle.

// Custom chrome: a borderless window you can drag by its header bar.
Stage win = new Stage(StageStyle.UNDECORATED);
stages.register("editor", win);
stages.makeDraggable(win, titleBar);   // titleBar is a Node in the scene
stages.fitToScreen(win);

RecommendationsRecomendaciones

Do register every secondary window you'll touch again, and use close(key) to close + unregister together (avoids leaking stale registry entries).Registra toda ventana secundaria que vayas a volver a tocar, y usa close(key) para cerrar + desregistrar a la vez (evita dejar entradas obsoletas en el registro).

Do lean on the automatic FX-thread marshalling — call straight from background tasks.Apóyate en el marshalling automático al hilo de FX — llama directamente desde tareas en segundo plano.

Prefer fitToScreen over OS-maximize when you want a full-bleed window that still behaves like a normal, movable window.Prefiere fitToScreen sobre el maximizado del SO cuando quieras una ventana a sangre completa que siga comportándose como una ventana normal y movible.