• category: swing folder: FileChooserFileAndFilterAlignment title: JFileChooserのファイル名とフィルタのラベルを右揃えに変更する tags: [JFileChooser, JLabel, BoxLayout] author: aterai pubdate: 2017-08-28T15:46:15+09:00 description: JFileChooserの下部に表示されるファイル名とフィルタのラベルを左揃えから右揃えに変更します。 image: https://drive.google.com/uc?export=view&id=

概要

JFileChooserの下部に表示されるファイル名とフィルタのラベルを左揃えから右揃えに変更します。

サンプルコード

class RightAlignmentMetalFileChooserUI extends MetalFileChooserUI {
  protected RightAlignmentMetalFileChooserUI(JFileChooser fc) {
    super(fc);
  }
  @Override public void installComponents(JFileChooser fc) {
    super.installComponents(fc);
    SwingUtils.stream(getBottomPanel())
      .filter(JLabel.class::isInstance)
      .map(JLabel.class::cast)
      .forEach(l -> {
        l.setHorizontalAlignment(SwingConstants.RIGHT);
        l.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
      });
  }
}

class RightAlignmentWindowsFileChooserUI extends WindowsFileChooserUI {
  protected RightAlignmentWindowsFileChooserUI(JFileChooser fc) {
    super(fc);
  }
  @Override public void installComponents(JFileChooser fc) {
    super.installComponents(fc);
    SwingUtils.stream(getBottomPanel())
      .filter(JLabel.class::isInstance)
      .map(JLabel.class::cast)
      .forEach(l -> l.setAlignmentX(1f));
  }
}
View in GitHub: Java, Kotlin

解説

  • MetalLookAndFeel
    • MetalFileChooserUI#getBottomPanel()で取得できるJPanelのレイアウトはBoxLayout.Y_AXISで、以下の3つのJPanelを縦配置
      • ファイル名ラベルとファイル名入力欄を配置したfileNamePanel(BoxLayout.LINE_AXIS)
      • ファイルフィルタラベルとファイルフィルタコンボボックスを配置したfilesOfTypePanel(BoxLayout.LINE_AXIS)
      • approveButtonなどを配置したButtonPanel(FlowLayout風の独自ButtonAreaLayout)
    • 各ラベルの推奨サイズを文字列の長い方に合わせることで、別パネルに分かれていても位置が揃うように設定されているため、JLabel#setHorizontalAlignment(SwingConstants.RIGHT)で右揃えに変更可能
  • WindowsLookAndFeel
    • WindowsFileChooserUI#getBottomPanel()で取得できるJPanelのレイアウトはBoxLayout.LINE_AXISで、以下の3つのJPanelを横配置
      • ファイル名ラベルとファイル名入力欄を配置したfileNamePanel(BoxLayout.Y_AXIS)
      • ファイルフィルタラベルとファイルフィルタコンボボックスを配置したfilesOfTypePanel(BoxLayout.Y_AXIS)
      • approveButtonなどを配置したButtonPanel(BoxLayout.Y_AXIS)
    • 各ラベルはBoxLayout.Y_AXISJPanelにまとめられているので、JComponent.html#setAlignmentX(1f)で右揃えに変更可能

参考リンク

コメント