TITLE:LookAndFeelの一覧を取得する

Posted by terai at 2009-01-19

LookAndFeelの一覧を取得する

インストールされているLookAndFeelの一覧を取得し、これらを切り替えるためのメニューバーを作成します。SwingSet3からの引用です。

  • &jnlp;
  • &jar;
  • &zip;

#screenshot

サンプルコード

private ButtonGroup lookAndFeelRadioGroup;
private String lookAndFeel;
protected JMenu createLookAndFeelMenu() {
  JMenu menu = new JMenu("LookAndFeel");
  lookAndFeel = UIManager.getLookAndFeel().getClass().getName();
  lookAndFeelRadioGroup = new ButtonGroup();
  for(UIManager.LookAndFeelInfo lafInfo: UIManager.getInstalledLookAndFeels()) {
    menu.add(createLookAndFeelItem(lafInfo.getName(), lafInfo.getClassName()));
  }
  return menu;
}
protected JRadioButtonMenuItem createLookAndFeelItem(String lafName, String lafClassName) {
  JRadioButtonMenuItem lafItem = new JRadioButtonMenuItem();
  lafItem.setSelected(lafClassName.equals(lookAndFeel));
  lafItem.setHideActionText(true);
  lafItem.setAction(new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
      ButtonModel m = lookAndFeelRadioGroup.getSelection();
      try{
        setLookAndFeel(m.getActionCommand());
      }catch(Exception ex) {
        ex.printStackTrace();
      }
    }
  });
  lafItem.setText(lafName);
  lafItem.setActionCommand(lafClassName);
  lookAndFeelRadioGroup.add(lafItem);
  return lafItem;
}
public void setLookAndFeel(String lookAndFeel) throws ClassNotFoundException,
      InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
  String oldLookAndFeel = this.lookAndFeel;
  if (oldLookAndFeel != lookAndFeel) {
    UIManager.setLookAndFeel(lookAndFeel);
    this.lookAndFeel = lookAndFeel;
    updateLookAndFeel();
    firePropertyChange("lookAndFeel", oldLookAndFeel, lookAndFeel);
  }
}
private void updateLookAndFeel() {
  Window windows[] = Frame.getWindows();
  for(Window window : windows) {
    SwingUtilities.updateComponentTreeUI(window);
  }
}

解説

上記のサンプルでは、UIManager.getInstalledLookAndFeels()メソッドを使用してUIManager.LookAndFeelInfoのリストを取得しています。

参考リンク

コメント