• title: JOptionPaneで使用するボタンのサイズを揃える tags: [JOptionPane, JButton, UIManager, NimbusLookAndFeel] author: aterai pubdate: 2015-05-11T00:39:58+09:00 description: NimbusLookAndFeelでJOptionPaneを使用した場合、そのJButtonのサイズを揃えるかどうかを設定します。

概要

NimbusLookAndFeelJOptionPaneを使用した場合、そのJButtonのサイズを揃えるかどうかを設定します。java - JOptionPane button size (Nimbus LAF) - Stack Overflowの回答を参考にしています。

サンプルコード

UIManager.getLookAndFeelDefaults().put("OptionPane.sameSizeButtons", true);
View in GitHub: Java, Kotlin

解説

  • default
    • NimbusLookAndFeelのデフォルトでは、JOptionPaneで使用するJButtonのサイズは各ボタンのテキストの長さに依存する
    • 注: MetalLookAndFeelなどは、常にこれらのボタンは同じサイズ
  • SameSizeButtons
    • UIManager.getLookAndFeelDefaults().put("OptionPane.sameSizeButtons", true);で、最も長いボタンテキストから作成されるJButtonのサイズに揃えられる
    • 注: このサンプルでは、実行中にこれらを切り替えるテストを行うために、UIManager.getLookAndFeelDefaults()で取得したUIDefaultsではなく、以下のように新規作成したUIDefaultsOptionPane.sameSizeButtonsを設定してJOptionPaneに上書きし、SwingUtilities.updateComponentTreeUI(JOptionPane)UIを更新している(OptionPane.buttonAreaBorderでテスト)
      UIDefaults d = new UIDefaults();
      d.put("OptionPane.sameSizeButtons", true);
      op.putClientProperty("Nimbus.Overrides", d);
      op.putClientProperty("Nimbus.Overrides.InheritDefaults", true);
      SwingUtilities.updateComponentTreeUI(op);
      op.createDialog(getRootPane(), "title").setVisible(true);
      

参考リンク

コメント