Add persistent language selection with ConfigService integration

This commit is contained in:
Rithvik Sriram 2026-01-15 00:29:12 +01:00
commit 916fa07418
3 changed files with 86 additions and 3 deletions

View file

@ -19,6 +19,7 @@ import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import client.utils.LocaleManager;
import com.google.inject.Injector;
import javafx.fxml.FXMLLoader;
@ -38,7 +39,8 @@ public class MyFXML {
public <T> Pair<T, Parent> load(Class<T> c, String... parts) {
try {
var loader = new FXMLLoader(getLocation(parts), null, null, new MyFactory(), StandardCharsets.UTF_8);
var localeManager = injector.getInstance(LocaleManager.class);
var loader = new FXMLLoader(getLocation(parts), localeManager.getBundle(), null, new MyFactory(), StandardCharsets.UTF_8);
Parent parent = loader.load();
T ctrl = loader.getController();
return new Pair<>(ctrl, parent);

View file

@ -1,5 +1,6 @@
package client.utils;
import com.google.inject.Inject;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import java.util.Locale;
@ -10,13 +11,30 @@ public class LocaleManager {
private final ObjectProperty<ResourceBundle> currentBundle = new SimpleObjectProperty<>();
private static final String RESOURCE_BUNDLE_PATH = "locale/lang";
private final ConfigService configService;
@Inject
public LocaleManager(ConfigService configService) {
this.configService = configService;
String savedLanguage = configService.getConfig().getLanguage();
Locale initialLocale = Locale.forLanguageTag(savedLanguage);
currentLocale.set(initialLocale);
public LocaleManager() {
// TODO: Set currentLocale to config value instead of EN default.
updateBundle();
currentLocale.addListener((_, oldLocale, newLocale) -> {
updateBundle();
saveLanguagePreference(newLocale.getLanguage());
});
currentLocale.addListener((_, _, _) -> updateBundle());
}
private void saveLanguagePreference(String languageCode) {
configService.getConfig().setLanguage(languageCode);
configService.save();
}
private void updateBundle() {
ResourceBundle bundle = ResourceBundle.getBundle(RESOURCE_BUNDLE_PATH,
currentLocale.get(),
@ -44,4 +62,6 @@ public class LocaleManager {
public ObjectProperty<ResourceBundle> getBundleProperty() {
return currentBundle;
}
}