Files
NeitzelLib/fx/docs/i18n.md
T

2.2 KiB

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. Expose the service through ViewDependencies.findService(Localizer.class). With the Neitzel adapter, register it in the underlying ApplicationContext.

var language = new Localizer(initialLocale, Locale.ENGLISH,
        new Localizer.Catalog(MyApp.class, "MyApp", "org.example.myapp"),
        LanguageMenu.CATALOG);
context.addSingleton(Localizer.class, language);
var texts = language.forClass(AccountController.class);
label.setText(texts.text("account.saved", accountName));

Catalogs are UTF-8 properties files. For each key the search tries the requested locale's variants (for example de-CH before de), then variants of the fallback locale, then files without a language suffix. Each pass visits the view catalog beside its FXML, the controller's class catalog, package Messages catalogs up to the configured root, the named application catalog and the named library catalogs in registration order. For example, use Account_de.properties beside Account.fxml and MyApp_de.properties at the application resource root. Missing keys display as ⟦key⟧ and log once per locale and catalog context. Java calls with arguments use MessageFormat patterns.

ViewLoader supplies the same Messages bundle to the FXMLLoader and the controller. Use <Button text="%account.save"/> in FXML and @FXML private Messages resources; in the controller. A plain fx:include inherits the parent's bundle. Load reusable components separately for their own catalog. For an ordinary FXMLLoader, pass language.forView(location, controllerClass) as its ResourceBundle.

Change the language on the FX thread with language.setLocale(locale). Ordinary text lookups return a string immediately. Bind individual live labels with label.textProperty().bind(texts.observable("account.save")) or observe language.localeProperty() to refresh a view. FXML attributes resolve again when the view is recreated. LanguageMenu.create supplies a selector with an owner for its notice and a callback for saving a user selection. Pass a Messages bundle to DockingOptions.setResourceBundle for localized docking commands.