Skip to content

Java Library

Thomas Cashman edited this page Nov 19, 2020 · 7 revisions

The Java library provides classes for reading .po files and accessing translations.

Set Up

Add the following dependency to your Gradle or Maven build.

Gradle

compile "org.mini2Dx:gettext-lib:1.7.1"

Maven

<dependency>
    <groupId>org.mini2Dx</groupId>
    <artifactId>gettext-lib</artifactId>
    <version>1.7.1</version>
</dependency>

Usage

The main class used by developers is the GetText class.

The following example shows how to load a .po file and access its translations.

//TODO: Insert your file path here
File file = new File("app_fr.po");

//Parse the .po file and set it as French translation
PoFile poFile = new PoFile(Locale.FRENCH, file);

//Store the file in the GetText repository
GetText.add(poFile);

//Set the app's locale to French
GetText.setLocale(Locale.FRENCH);

//Retrieve the translation for a string
//Note: If the string is not in the .po file, the string itself is returned
String translation = GetText.tr("Close Application");

//It is also possible to insert values using java.text.MessageFormat
//{0} will be replaced with 77, {1} will be replaced with 2
translation = GetText.tr("{0} entries available - {1} remaining", 77, 2);

//.po contexts are also supported
translation = GetText.trc("contextName", "Close Application");

//.po plurals
translation = GetText.trn("Close Application", "Close Applications", 1);

//.po plurals with context
translation = GetText.trn("contextName", "Close Application", "Close Applications", 1);

For more methods, please refer to the Javadoc

Clone this wiki locally