ResourceBundle的封装,resourcebundle封装,这个类来自于jhotdr
分享于 点击 33154 次 点评:216
ResourceBundle的封装,resourcebundle封装,这个类来自于jhotdr
这个类来自于jhotdraw, 后来我自己做了一些改进
基类
/** * <B>AppResources</B> is a convenience wrapper for accessing resource * store in a <I>ResourceBundle<I>. * * @version Ver 1.1 2009-4-13 modify * @since Application Ver 1.1 <br> * * 1.1 keeping only the getString and getInteger method. <br> * 1.0 JHotDraw7 */public class AppResources { /** The wrapped resource bundle. */ protected final ResourceBundle resource; /** * Instantiates a new resourcebundleutil which wraps the provided resource * bundle. * @param r the ResourceBundle */ public AppResources(ResourceBundle r) { resource = r; } /** * Gets a string from the ResourceBundles. * <br> Convenience method to save casting. * * @param key the key of the properties. * * @return the value of the property. Return the key if the value is not found. */ public String getString(String key){ try { return resource.getString(key); } catch (MissingResourceException e) { return key; } } /** * a convenience mentod to get all strings as a sentence or phrase. * @since 1.1 */ public String getString(String ...keys) { StringBuilder sb = new StringBuilder(); for(String key:keys){ sb.append(getString(key)); sb.append(" "); } return sb.toString(); } public String getTips(String key) { String tips = key+".tips"; String retval = getString(tips); if(retval.equals(tips)){ retval= getString(key); } return retval; } /** * Gets the integer from the properties. * * @param key the key of the property. * * @return the value of the key. return -1 if the value is not found. */ public Integer getInteger(String key){ try { return Integer.valueOf(resource.getString(key)); } catch (MissingResourceException e) { return new Integer(-1); } } /** * Gets the int. * * @param key the key * * @return the int */ public int getInt(String key){ try { return Integer.parseInt(resource.getString(key)); } catch (NumberFormatException e) { return -1; // modify here if you need to throw a Exception here } } /** * Gets the bundle. * * @return the bundle */ public ResourceBundle getBundle(){ return resource; } /** * Gets the keys. * * @return the keys */ public Enumeration<String> getKeys(){ return resource.getKeys(); } /** * Gets a resource string formatted with MessageFormat. * * @param key the key * @param argument the argument * * @return Formatted stirng. */ public String getFormatted(String key, String argument) { return MessageFormat.format(resource.getString(key), new Object[] {argument}); } /** * Gets a resource string formatted with MessageFormat. * * @param key the key * @param arguments the arguments * * @return Formatted stirng. */ public String getFormatted(String key, Object... arguments) { return MessageFormat.format(resource.getString(key), arguments); } @Override public String toString() { return super.toString()+"["+resource+"]"; } public char getChar(String string) { try { return resource.getString(string).charAt(0); } catch (IndexOutOfBoundsException e) { return Character.MIN_VALUE; } }}
适用于Swing ResourceBundle封装
public class SwingResources extends AppResources{ protected SwingResources(ResourceBundle r) { super(r); } /** * Gets the resource bundle util. * * @param boundleName the full package name. * <p> * note: if the name wasn't a full name, the Local would be loaded. * * @return the resource bundle util * * @throws MissingResourceException the missing resource exception */ public static SwingResources getResources(String boundleName)throws MissingResourceException{ return new SwingResources(ResourceBundle.getBundle(boundleName,AppManager.getLocale()));// you can use Locale.getDefault() instead of AppManager... } /** * Gets the resource bundle util. * * @param boundleName the boundle name * @param locale the locale * * @return the resource bundle util * * @throws MissingResourceException the missing resource exception */ public static SwingResources getResources(String boundleName,Locale locale)throws MissingResourceException{ return new SwingResources(ResourceBundle.getBundle(boundleName,locale)); } public void configMenu(JMenuItem menu, String name) { menu.setText(getString(name)); if(!(menu instanceof JMenu)){// items menu.setAccelerator(getAcc(name)); } menu.setMnemonic(getMnem(name)); menu.setIcon(getImageIcon(name,getClass())); } public Icon getImageIcon(String key){ return getImageIcon(key,getClass()); } private Icon getImageIcon(String key, Class<?> clazz) { String src=""; try { src=resource.getString(key+".icon"); } catch (MissingResourceException e) { return null; } if (src.equals("")) { return null; } String imageDir=getImageDir(); if(!(imageDir.endsWith("/"))){ imageDir+="/"; } src = imageDir+src; return new ImageIcon(src); } private String getImageDir(){ String imageDir = resource.getString("icon.dir"); if(!(imageDir.endsWith("/"))){ imageDir+="/"; } return imageDir; } public Image getImage(String key) { String src=""; try { src=resource.getString(key+".icon"); String imageDir=getImageDir(); src = imageDir+src; return ImageIO.read(new File(src)); } catch (MissingResourceException e) { } catch (IOException e) { } return null; } private char getMnem(String key) { String string=null; try { string=resource.getString(key+".mnem");; } catch (MissingResourceException e) { } return (string==null||string.length()==0)?'\0':string.charAt(0); } /** * Gets the shortcut key. */ private KeyStroke getAcc(String key) { KeyStroke keyStroke=null; String string=null; try { string=resource.getString(key+".acc"); } catch (MissingResourceException e) { } keyStroke = (string==null)?(KeyStroke)null:KeyStroke.getKeyStroke(string); return keyStroke; } /** * config swing action */ public void configAction(Action action, String id) { configAction(action, id,getClass()); } private void configAction(Action action, String id, Class<?> clazz) { action.putValue(Action.NAME, getString(id)); action.putValue(Action.ACCELERATOR_KEY, getAcc(id)); action.putValue(Action.MNEMONIC_KEY, new Integer(getMnem(id))); action.putValue(Action.SMALL_ICON, getImageIcon(id, clazz)); action.putValue(Action.SHORT_DESCRIPTION, getString(id)); } public void configDialog(JDialog dialog, String name) { dialog.setTitle(getString(name)); dialog.setIconImage(getImage(name)); } public void configWindow(JFrame frame, String id) { frame.setTitle(getString(id+".title")); } /** * Config JLabel. */ public void configLabel(JLabel label, String id) { label.setText(getString(id+".label.text"));//$NON-NLS-1$ } public void configToolbarButton(JToggleButton t,String id) { Icon icon=getImageIcon(id); if(icon ==null){ t.setText(getString(id)); }else{ t.setIcon(icon); t.setText(null); } t.setToolTipText(getString(id+".tips"));//$NON-NLS-1$ } public void configTray(SystemTrayProxy tray) { tray.setToolTip(getString("system"));//$NON-NLS-1$ tray.setImage(getImage("system")); } /// --------- for Application /** * Config view. */ public void configView(View view, String id) { view.setTitle(getString(id+".title"));//$NON-NLS-1$ } public void configConfigItem(ConfigItem item) { String name=item.getLabel()+".config"; //$NON-NLS-1$ item.setIcon(getImage(name)); item.setLabel(getString(name)); } public void configGuiderContent(AbsGuiderContent content, String id) { content.setTitle(getString(id+".title"));//$NON-NLS-1$ content.setContent(getString(id+".content"));//$NON-NLS-1$ }}
用于JavaFX2 的ResourceBundle
public class FXResources { public FXResources(ResourceBundle r) { super(r); } @Override public ResourceBundle getBundle(){ return resource; } public static FXResources getResources(Class<?> c) { return getResources(c.getPackage().getName()+".Labels"); } public static FXResources getResources(String boundleName)throws MissingResourceException{ return new FXResources(ResourceBundle.getBundle(boundleName,AppManager.getLocale())); } public static AppResource getResources(String boundleName,Locale locale)throws MissingResourceException{ return new AppResource(ResourceBundle.getBundle(boundleName,locale)); } @Override protected KeyCombination getAcc(String key){ String string=null; try { string=resource.getString(key+".acc"); if(string==null){ return null; }// return KeyCombination.valueOf(string);// String[] keys = string.split(" "); if(keys.length==1){ return KeyCombination.valueOf(string); } KeyCode mainKey =KeyCode.getKeyCode(keys[keys.length-1]); Modifier[] modifiers=new Modifier[keys.length-1]; for(int i=0,j=keys.length-1;i<j;i++){ modifiers[i]=getModifier(keys[i]); } return new KeyCodeCombination(mainKey, modifiers); } catch (MissingResourceException e) { return null; } } private Modifier getModifier(String key) { if(key.equals("ctrl")){ return KeyCodeCombination.CONTROL_DOWN; } if(key.equals("shift")){ return KeyCodeCombination.SHIFT_DOWN; } if(key.equals("alt")){ return KeyCodeCombination.ALT_DOWN; } return null; } private String getTips(String key) { String tips = key+".tips"; String retval = getString(tips); if(retval.equals(tips)){ retval= getString(key); } return retval; } @Override public char getChar(String string) { try { return resource.getString(string).charAt(0); } catch (IndexOutOfBoundsException e) { return Character.MIN_VALUE; } } private Node getImageView(String key) { return new ImageView(getImage(key)); } @Override public void configView(View view, String id) { view.setTitle(getString(id+".title")); configScene(view.getScene(),id); } @Override public Image getImage(String key) { String src=""; try { src=resource.getString(key+".icon"); } catch (MissingResourceException e) { return null; } if (src.equals("")) { return null; } String imageDir=getImageDir(); if(!(imageDir.endsWith("/"))){ imageDir+="/"; } src = imageDir+src; return new Image(src); } private String getImageDir(){ String imageDir = AppManager.getPreference(Application.class.getName()).get("icon.dir"); if(!(imageDir.endsWith("/"))){ imageDir+="/"; } return imageDir; } @Override public void configScene(Scene scene) { configScene(scene, scene.getRoot().getId()); } @Override public void configScene(Scene scene, String id) { try { scene.getStylesheets().add(getCSS()+id+".css"); } catch (Exception e) {// AppOptionDialog.showTips(e.getMessage(), AppManager.getPrimaryStage()); } } private String getCSS() { return AppManager.getPreference(Application.class.getName()).get("css"); } @Override public String setTooltip(Control c,String key) { String tips=getTips(key); c.setTooltip(getTooltip(tips)); return tips; } @Override public Tooltip getTooltip(String tips){ Tooltip tooltip=new Tooltip(tips); tooltip.setAutoHide(false); return tooltip; } @Override public Button configButton(String key) { Button button=new Button(getString(key)+getMnem(key),getImageView(key)); button.setMaxWidth(Double.MAX_VALUE); button.setMaxHeight(Double.MAX_VALUE);// button.setPrefHeight(25); button.setContentDisplay(ContentDisplay.LEFT); setTooltip(button,key); return button; } @Override public Button configButton(AppHandler<? super ActionEvent> handler) { Button button=configButton(handler.getId()); button.addEventHandler(ActionEvent.ACTION, handler); button.disableProperty().bindBidirectional(handler.disableProperty()); return button; } @Override public TextField configTextField(String key) { TextField filed = new TextField(); filed.setMaxWidth(Double.MAX_VALUE); filed.setMaxHeight(Double.MAX_VALUE); filed.setPromptText(setTooltip(filed, key)); return filed; } @Override public Label configLabel(String key){ String string = getString(key); Label label = new Label(string,getImageView(key)); label.setMinWidth(string.length()*13); setTooltip(label, key); return label; }// public Label configLabel(AppHandler<ActionEvent> h) {// Label l=configLabel(h.getId());// l.addEventHandler(InputEvent.ANY, h);// return l;// } @Override public MenuItem configMenuItem(String key) { MenuItem item = new MenuItem(getString(key)+getMnem(key),getImageView(key)); KeyCombination keyCombination =getAcc(key); if(keyCombination!=null){ item.setAccelerator(getAcc(key)); } return item; } @Override public MenuItem configMenuItem(AppHandler<ActionEvent> h) { MenuItem item =configMenuItem(h.getId()); item.setOnAction(h); return item; }}
适用于SWT/JFace的ResourceBundle的封装
//由于JFace已经提供了完善的I18N机制, 出于易于交流的目的, 不建议使用此类. public class PluginResources extends AppResources{ private final String pluginID; private PluginResources(String pluginID,ResourceBundle r) { super(r); this.pluginID = pluginID; } protected static PluginResources getResources(String pluginID,Class<?> c) { return getResources(pluginID,c.getPackage().getName()+".Labels", Locale.getDefault(),c); } protected static PluginResources getResources(String pluginID,Class<?> c,Locale locale) { return getResources(pluginID,c.getPackage().getName()+".Labels", locale,c); } protected static PluginResources getResources(String pluginID,String baseName,Locale locale,Class<?> c) { return new PluginResources(pluginID,ResourceBundle.getBundle(baseName, locale,c.getClassLoader())); } public ImageDescriptor getImageDescriptor(String key) { String src=""; try { src=resource.getString(key+".icon"); String imageDir=getImageDir(); src = imageDir+src; ImageDescriptor id = AbstractUIPlugin.imageDescriptorFromPlugin(pluginID, src); return id; } catch (MissingResourceException e) { } return null; } public Image getImage(String key) { ImageDescriptor desc = getImageDescriptor(key); return desc==null?null:desc.createImage(); } public void configAction(Action action,String id) { action.setText(getString(id)); action.setToolTipText(getTips(id)); ImageDescriptor image =getImageDescriptor(id); action.setImageDescriptor(image); action.setHoverImageDescriptor(image); } public String getTips(String key) { return getAdditionMessage(key,".tips"); } public String getErrorTips(String key) { return getAdditionMessage(key,".error"); } private String getAdditionMessage(String key,String addition){ String tips = key+addition; String retval = getString(tips); if(retval.equals(tips)){ retval= getString(key); } return retval; }}
Labels_en_US.properties
new=Newnew.mnem=Nnew.acc=ctrl Nnew.icon=fileNew.pngframeTitle={0}{2,choice,1\#|1< {2}} - {1}cancel=CanceldontSave=Don't SavecouldntSave=Couldn''t save to the file "{0}"
使用实例
public class SharedResources{ private static String DEFAULT_LABEL= SharedResources.class.getPackage().getName()+".Labels"; private static Map<String, PluginResources> resourceMap=new HashMap<>(8); /** return the default label which contains basic resource(eg:"file","edit",etc) */ public static PluginResources getResources() { return getResources(ID, JeeleeActivator.class); } public static PluginResources getResources(String pluginID,Class<?> clazz) { return getResources(pluginID, clazz, clazz.getPackage().getName()+".Labels"); } public static PluginResources getResources(String pluginID, Class<?> clazz, String baseName) { PluginResources r= resourceMap.get(pluginID); if(r==null){ r=PluginResources.getResources(pluginID,baseName,locale,clazz); resourceMap.put(clazz.getName(), r); } return r; }... ...}
用户点评