Swing Application Framework その3:リソース管理

たいていのアプリケーションはテキストやアイコン、フォント定義などの、共通的なリソースを使用します。フレームワークでは、このリソースファイルの管理を統一的に扱う仕組みが用意されています。リソースファイルは、Applicationのサブクラス名に".properties"を付けた名前で、Applicationのサブクラスと同階層のresourcesディレクトリ内のものが使用されます。

リソースの明示的読み込み

リソースファイルはフレームワーク提供のResourceManagerクラスから取得できるResourceMapクラスによって扱うことができます。

  @Override
  protected void initialize(String[] args) {
    ApplicationContext ctxt = getContext();
    ResourceManager mgr = ctxt.getResourceManager();
    resource = mgr.getResourceMap(HelloWorld.class);
  }

  @Override
  protected void startup() {
    label = new JLabel();
    String helloText = (String) resource.getObject("helloLabel", String.class);
    ・・・・
  }

resources/HelloWorld.propertiesというプロパティファイルを用意し、以下の記述をしておくと、上記コード中のhelloTextというStringへ値を読み込むことができます。

helloLabel = Hello, world!

リソースインジェクションの利用

フレームワークは使用するコンポーネントに自動的にリソースをインジェクションできます。この処理はアプリケーションのルートウインドウに定義したコンポーネントに対して、再帰的にリソースの埋め込みが行われます。
リソースインジェクションは、コンポーネントのsetNameメソッドにて与えられた名前に基づき行われます。

  JButton btnShowTime;
  JTextField txtShowTime;

  @Override
  protected void startup() {
    timePanel = new JPanel();
    btnShowTime = new JButton();
    txtShowTime = new JTextField();

    btnShowTime.setName("btnShowTime");
    txtShowTime.setName("txtShowTime");

  }

リソースファイルに以下の記載をしておくことで、対応する名前の属性を自動的に設定してくれます。

btnShowTime.text = Show current time!
btnShowTime.icon = refresh.png

txtShowTime.text = Press the button to retrieve time.
txtShowTime.editable = false

フィールドリソースインジェクションの利用

  public class NameEntryPanel extends javax.swing.JPanel {

    @Resource
    String greetingMsg;

    ApplicationContext ctx;
    ResourceMap resource;

    public NameEntryPanel(ApplicationContext ctxt) {
        initComponents();
        ResourceMap resource = ctxt.getResourceMap(NameEntryPanel.class);
        resource.injectFields(this);
    }
  }

リソースファイルに以下の記載をしておくことで、@Resourcdアノテーションへ値がインジェクションされます。.の指定がデフォルトですが、@Resource アノテーションで直接指定することも可能です。

# resources/NameEntryPanel.properties
NameEntryPanel.greetingMsg = Hello, %s, this string was injected!

ResourceMapクラスの型変換

以下のリソースファイルがあった場合、

# resources/Converter.properties
msg1 = This app demos.
msg2 = This is %s.
color = #BB0000
font = Arial-BOLD-22
icon = next.png

アプリケーションから以下の様に、型を指定してオブジェクトを取得することもできます。

    ApplicationContext ctx = getContext();
    ResourceMap resource = ctx.getResourceMap();

    String msg1 = resource.getString("msg");
    String msg2 = resource.getString("msg", "ResourceConverter");
    Color color = resource.getColor("color");
    Font font = resource.getFont("font");
    Icon icon = resource.getIcon("icon");