package application; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Paths; import java.util.Locale; import java.util.ResourceBundle; /*********************************************************************** * アプリケーションの言語を切り替える(シングルトン) */ public class ApplicationLanguage { private Locale locale = null; private ResourceBundle resBundle = null; private static ApplicationLanguage instance = null; private final static String RESOURCE_PATH = "resources/locales/"; public final static String JP = "ja"; public final static String EN = "en"; /*********************************************************************** /*********************************************************************** * [ *constructor ] /*********************************************************************** * * @return */ private ApplicationLanguage() { this.locale = Locale.getDefault(); setLocaleLanguage(this.locale.getLanguage()); } /*********************************************************************** /*********************************************************************** * [ *public static ] /*********************************************************************** * */ public static ApplicationLanguage getInstance() { if (instance == null) instance = new ApplicationLanguage(); return instance; } /*********************************************************************** /*********************************************************************** * [ *public ] /*********************************************************************** * ローカルの .properties から言語情報を切り替え. * @param language 変更先の言語 */ public void setLocaleLanguage(final String language) { URL resURL = null; try { File resDir = Paths.get(RESOURCE_PATH).toFile(); // for Eclipse project resURL = resDir.toURI().toURL(); } catch (MalformedURLException e) { e.printStackTrace(); } // resURL = this.getClass().getClassLoader().getResource(RESOURCE_PATH); // for executable jar URLClassLoader urlLoader = new URLClassLoader(new URL[] { resURL }); this.resBundle = ResourceBundle.getBundle(language, this.locale, urlLoader); // // Another approach. // properties = new Properties(); // try { // properties.load(Main.class.getClassLoader().getResourceAsStream(RESOURCE_PATH + language + ".properties")); // } catch (IOException e) { // return; // } } /*********************************************************************** * オプション名に対応した名前を返す. * @param propName 取得したいプロパティの名前 */ public String getOptionByPropName(final String propName) { // return properties.getProperty(propName); return this.resBundle.getString(propName); } }