March_hare
往往写发送消息都得 sendMessage("写死**");而且还不能转换成其他语言。


1. 创建语言文件
在` src/main/resources ` 下创建 lang_zh_CN.properties

代码:

  1. test=qwwwwwq
  2. test.t1=www {0}
  3. test.help=www {0} {1}
  4. test.help.add=添加
  5. #test.help.add=\u6dfb\u52a0
  6. #如果中文出现乱码或者无法加载,请使用Unicode编码

PS: lang_是根据baseName来定的,如果想改成其他的,比如 zzz_zh_CN,则ResourceBundle.getBundle("zzz",new Locale("zh","CN"));


2. 创建I18n类

代码:

  1. import java.util.Locale;
  2. import java.util.ResourceBundle;

  3. public class I18n {

  4.   private static ResourceBundle bundle;

  5.   public enum LANGUAGE {
  6.     SIMPLIFIED_CHINESE(new Locale("zh", "CN")), ENGLISH(new Locale("en", "US"));

  7.     Locale locale;

  8.     LANGUAGE(Locale locale) {
  9.    this.locale = locale;
  10.     }

  11.     public Locale getLocale() {
  12.    return locale;
  13.     }

  14.   }

  15.   /**
  16.    * 初始化
  17.    *
  18.    * @param lang
  19.    */
  20.   public static void init(LANGUAGE lang) {
  21.     bundle = ResourceBundle.getBundle("lang", lang.getLocale());
  22.   }

  23.   /**
  24.    *
  25.    * @param msgid
  26.    * @return
  27.    */
  28.   public static String __(String msgid) {
  29.     return bundle.getString(msgid);
  30.   }

  31.   public static void main(String[] args) {
  32.     I18n.init(LANGUAGE.SIMPLIFIED_CHINESE);
  33.     System.out.println(I18n.__("test.help.add"));
  34.   }
  35. }

3. 初始化&调用
在JavaPlugin里的onLoad方法初始化.

代码:

  1. @Override
  2.   public void onLoad() {
  3.     I18n.init(LANGUAGE.SIMPLIFIED_CHINESE);
  4.   }
如果想使用命令来更换语言的话(/xxx lang en)


直接 I18n.init(LANGUAGE.xxx); 就好了


调用

代码:

  1. public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {

  2.                 sender.sendMessage(I18n.__("test")); // 发送 qwwwwwq
  3.                 sender.sendMessage(MessageFormat.format(I18n.__("test.t1"), "qaq")); // 发送 www qaq
  4.                 sender.sendMessage(MessageFormat.format(I18n.__("test.help"), "qaq", "awaa")); // 发送 www qaq awaa
  5.                 sender.sendMessage(I18n.__("test.help.add")); // 发送 添加

  6.                 return super.onCommand(sender, command, label, args);
  7. }








第一页 上一页 下一页 最后一页