昨天说了ZK的国际化做得不够好,今天稍微试了下,发现昨天提到的方案是可行的,创建一个Initiator,自动的把文本替换为国际化的内容:
<?init class="xxx.I18nBinderInit"?>
<toolbarbutton label="button.add" image="../images/add.png" onClick="userListWindow.onAdd()"/>

这个只是原型,现在可能还不能处理所有的组件类型,可以简单的修改下变成通用的解决方案:
增加一个Property文件,里面添加需要处理的组件类型以及需要处理的属性,然后读取这个配置,如果谁觉得不够可以在classpath中放置一个同名的配置文件进行定制。
源代码:

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.util.Initiator;
import org.zkoss.zul.api.Window;
import org.zkoss.zul.api.Label;
import org.zkoss.zul.impl.api.LabelElement;
import org.zkoss.util.resource.Labels;

import java.util.Collection;

public class I18nBinderInit implements Initiator
{
    public void doInit(Page page, Object[] objects) throws Exception
    {
    }

    public void doAfterCompose(Page page) throws Exception
    {
        changeComponent(page);
    }

    private String getLabel(String key)
    {
        return Labels.getLabel(key,key);
    }

    private void applyComponent(Object component)
    {
        if (component instanceof LabelElement)
        {
            LabelElement label=(LabelElement) component;
            label.setLabel(getLabel(label.getLabel()));
        }
        else if (component instanceof Window)
        {
            Window window=(Window)component;
            window.setTitle(getLabel(window.getTitle()));
        }
        else if (component instanceof Page)
        {
            Page page=(Page)component;
            page.setTitle(getLabel(page.getTitle()));
        } else if (component instanceof Label)
        {
            Label label=(Label)component;
            label.setValue(getLabel(label.getValue()));
        }
    }

    private void changeComponent(Object component)
    {
        applyComponent(component);
        Collection<Component> children;
        if (component instanceof Page)
        {
            children = ((Page) component).getRoots();
        }
        else
        {
            children = ((Component) component).getChildren();
        }
        for (Component child : children)
        {
            changeComponent(child);
        }
    }

    public boolean doCatch(Throwable throwable) throws Exception
    {
        return false;
    }

    public void doFinally() throws Exception
    {

    }
}

(Visited 221 times, 1 visits today)