Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I translate text in .java source files?

I have an enum like this

public enum CheckboxFeature {

    Option1(" choose this"),
    Option2(" or this"),
    Option3(" maybe this"),
    Option4(" lastly this");

    @Getter
    private final String text;

    public static CheckboxFeature fromName(String v) {
        for (CheckboxFeature c: CheckboxFeature.values()) {
            if (c.name().equalsIgnoreCase(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }
}

This shows the four options as checkboxes in the web view

<form:checkboxes items="${features}" path="enabledFeatures" itemLabel="text" delimiter="<br/>"/>

How can I translate these options? I use fmt:message for the rest of the translations in the web view.

I have tried

Option1(" <fmt:message key=\"text.test\"/>"),

and

Option1(" ${option1}"),

with

<fmt:message key="text.select" var="option1"/>

in the .jsp. Neither of them work, so it seems it can't work this way. What is the correct way of translating the strings? Ideally using the fmt:message and i18n resources (lang.properties files) that are in place and working on the rest of the servlet?

like image 992
Fid Avatar asked Aug 05 '18 07:08

Fid


People also ask

What is the translator use in Java?

Java interpreter is a computer program (system software) that implements the JVM. It is responsible for reading and executing the program. It is designed in such a way that it can read the source program and translate the source code instruction by instruction.

How do I use Google Translate API in my Java application?

You can use google script which has FREE translate API. All you need is a common google account and do these THREE EASY STEPS. 2) Click Publish -> Deploy as webapp -> Who has access to the app: Anyone even anonymous -> Deploy. And then copy your web app url, you will need it for calling translate API.


1 Answers

Optimally, you get the resource key from the enum, and look that up.

public enum CheckboxFeature {
    Option1("label.option1.key"),
    Option2("label.option2.key"),
    Option1("label.option3.key"),
    Option2("label.option4.key");

    private final String key;
    [...]

I don't know how to nest a l10n lookup in the itemLabel attribute, so I would write something like:

<c:forEach items="Options.values()" var="current">
    <form:checkbox path="selectedOptions" value="${current.name()}"/> <fmt:message key="${current.getKey()}"/>
</c:forEach>
like image 62
DavidW Avatar answered Sep 28 '22 05:09

DavidW