All Downloads are FREE. Search and download functionalities are using the official Maven repository.

moreswing.swing.i18n.LocaleManager.scala Maven / Gradle / Ivy

The newest version!
package moreswing.swing.i18n

import java.text.MessageFormat
import java.util. { Locale, MissingResourceException }

import moreswing.util.ResourceBundleUtf8

import scala.collection.mutable.Buffer
import scala.ref.WeakReference

/** Manage all components with locale support.
 *
 * @author myst3r10n
*/
object LocaleManager {

  /** Add local listener.
   *
   * @param listener The locale listener.
   */
  def +=(listener: LocaleListener) {

    listeners += new WeakReference(listener)
    listener.localeChanged

  }

  /** Get locale
   *
   * @return The locale.
   */
  def locale = localeInstance

  /** Set locale
   *
   * @param locale Locale.
   */
  def locale_= (locale: Locale) {

    localeInstance = locale
    listeners.foreach { listener =>

      if(listener.get.orNull != null)
	      listener.get.get.localeChanged
      else
	      listeners.remove(listeners.indexWhere(l => l.get == listener.get))

    }
  }

  /** Get translated text.
   *
   * @param key The key inside resource bundle.
   */
  def text(key: String): String = try {

    if(key == null)
      ""
    else
      ResourceBundleUtf8.bundle("i18n/Messages", locale).getString(key)

  } catch { case e: MissingResourceException => key }

  /** Get translated text with substitution.
   *
   * @param key The key inside resource bundle.
   * @param arguments The arguments where should be substituted.
   */
  def text(key: String, arguments: Any*): String = try {

    if(key == null)
      ""
    else
      MessageFormat.format(text(key), arguments.map(_.asInstanceOf[AnyRef]): _*)

  } catch { case e: MissingResourceException => key }


  protected var localeInstance = new Locale("en", "US")
  protected var listeners = Buffer[WeakReference[LocaleListener]]()

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy