Text handling in Java views

1

In Android there is a handling of the texts and the views relating them in "values / strings.xml". To facilitate translations and reuse of text, the question is:

How to implement something similar in Java desktop projects?

I already appreciate the interest.

    
asked by Jomazao 02.05.2017 в 20:27
source

2 answers

1

I do not know if there is a direct way for the translation in java, but a solution can be with static classes. for example

public class Espanyol {
  static final Map<String , String> PALABRAS = new HashMap<String , String>() {{
    put("Hello",    "Hola");
    put("World", "Mundo");
  }};
}

The same for English

public class ingles{
  static final Map<String , String> PALABRAS = new HashMap<String , String>() {{
    put("Hello",    "Hello");
    put("World", "World");
  }};
}

Then you create a class that is the one that will identify the language

public class Traduccion {
  private idioma;
  public Traduccion(string idioma) {
    this.idioma = idioma;
  }
}

public string palabra(String key) {
  if(idioma.equals("es")) {
    return Espanyol.PALABRAS.get(key);
  } else {
    return Ingles.PALABRAS.get(key);
}

in your class you would have to create the translation object and pass the language to it.

Traduccion t = new Traduccion("es");
System.out.println(t.palabra("Hello") + t.palabra("world"));

This would print you hello world, if you change the label it would print you hello world

    
answered by 02.05.2017 в 21:14
1

You can use a property file as I show you in the following example:

import java.util.Locale;
import java.util.ResourceBundle;

public class Sample 
{

    public static void main (String[]args)
    {
        Locale español = new Locale("es");
        printProperty(español);

        Locale ingles = new Locale("en");
        printProperty(ingles);
    }

    public static void printProperty(Locale locale)
    {
        ResourceBundle rb = ResourceBundle.getBundle("propiedades", locale);
        System.out.println(rb.getString("idioma"));
        System.out.println(rb.getString("nombre"));
        System.out.println(rb.getString("mensaje"));
        System.out.println();
    }
}

Your project structure should look like this:

That's what each property file is (you should create it as new -> file)

Properties_es.properties:

idioma:español
nombre:Charbel
mensaje:mensaje de prueba

Properties_en.properties:

idioma:ingles
nombre:Charbel
mensaje:sample message
    
answered by 02.05.2017 в 22:41