概要

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

サンプルコード

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() {
    @Override 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.equals(lookAndFeel)) {
    UIManager.setLookAndFeel(lookAndFeel);
    this.lookAndFeel = lookAndFeel;
    updateLookAndFeel();
    firePropertyChange("lookAndFeel", oldLookAndFeel, lookAndFeel);
  }
}
private void updateLookAndFeel() {
  for (Window window: Frame.getWindows()) {
    SwingUtilities.updateComponentTreeUI(window);
  }
}
view all

解説

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

参考リンク

コメント