• category: swing folder: AuxiliaryLookAndFeel title: AuxiliaryLookAndFeelを追加する tags: [LookAndFeel, AuxiliaryLookAndFeel, UIManager, JComboBox] author: aterai pubdate: 2012-04-09T14:26:00+09:00 description: AuxiliaryLookAndFeelを追加して、WindowsLookAndFeelの場合の動作を変更します。 image: https://lh4.googleusercontent.com/-SxIyCqWRFhk/T4JxXw96NSI/AAAAAAAABLQ/gM_5mjZPn1o/s800/AuxiliaryLookAndFeel.png

概要

AuxiliaryLookAndFeelを追加して、WindowsLookAndFeelの場合の動作を変更します。

サンプルコード

JCheckBox check = (JCheckBox) e.getSource();
String lnf = UIManager.getLookAndFeel().getName();
if (check.isSelected() && lnf.contains("Windows")) {
  UIManager.addAuxiliaryLookAndFeel(auxLookAndFeel);
} else {
  UIManager.removeAuxiliaryLookAndFeel(auxLookAndFeel);
}
SwingUtilities.updateComponentTreeUI(getRootPane());
View in GitHub: Java, Kotlin

解説

WindowsLookAndFeelの場合、それを修正することなく、JComboBoxのドロップダウンリストで右クリックを無効にするようなComboBoxUIUIManager.addAuxiliaryLookAndFeel(...)を使って追加しています。

public class AuxiliaryWindowsComboBoxUI extends WindowsComboBoxUI {
  public static ComponentUI createUI(JComponent c) {
    return new AuxiliaryWindowsComboBoxUI();
  }
  @Override protected ComboPopup createPopup() {
    return new BasicComboPopup2(comboBox);
  }
  @Override public void addEditor() {
    removeEditor();
    ComboBoxEditor cbe = comboBox.getEditor();
    if (cbe != null) {
      editor = cbe.getEditorComponent();
      if (editor != null) {
        configureEditor();
        comboBox.add(editor);
        if (comboBox.isFocusOwner()) {
          editor.requestFocusInWindow();
        }
      }
    }
  }
  //Override all UI-specific methods your UI classes inherit.
  @Override public void removeEditor() {}
  @Override protected void configureEditor() {}
  @Override protected void unconfigureEditor() {}
  @Override public void update(Graphics g, JComponent c) {}
  @Override public void paint(Graphics g, JComponent c) {}
  //...
  • 注:
    • LookAndFeelNimbusにするとClassCastExceptionが発生する
    • UIManager.addPropertyChangeListener(new PropertyChangeListener() {...});を追加して、WindowsLookAndFeel以外の場合は、UIManager.removeAuxiliaryLookAndFeel(auxLookAndFeel);
    • 編集可能なJComboBoxの場合、NullPointerExceptionが発生する
      • WindowsComboBoxUI#addEditor()をオーバーライド

参考リンク

コメント