LookAndFeelの一覧を取得する
Total: 14728
, Today: 1
, Yesterday: 0
Posted by aterai at
Last-modified:
概要
インストールされているLookAndFeel
の一覧を取得し、これらを切り替えるためのメニューバーを作成します。このサンプルは、Swingset3
からの引用です。
Screenshot
Advertisement
サンプルコード
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: Window.getWindows()) {
SwingUtilities.updateComponentTreeUI(window);
}
}
View in GitHub: Java, Kotlin解説
上記のサンプルでは、UIManager.getInstalledLookAndFeels()
メソッドを使用してUIManager.LookAndFeelInfo
のリストを取得しています。
参考リンク
Swingset3- Look and Feelの変更
SwingSet2
版は予めLookAndFeel
のリストを用意する必要がある