• category: swing folder: PrototypeDisplayValue title: JComboBoxのセルサイズを決定するためのプロトタイプ値を設定する tags: [JComboBox, ListCellRenderer] author: aterai pubdate: 2015-05-18T00:01:40+09:00 description: JComboBoxがそのセルサイズを決定するために使用するプロトタイプ値を設定します。 image: https://lh3.googleusercontent.com/-DafUFitik9w/VVidadY7TNI/AAAAAAAAN4U/D40YKz8mMUY/s800/PrototypeDisplayValue.png

概要

JComboBoxがそのセルサイズを決定するために使用するプロトタイプ値を設定します。

サンプルコード

combo3.setPrototypeDisplayValue(TITLE);
#spandel
//...
#spanend
#spanadd
// ...
#spanend
combo5.setRenderer(new SiteListCellRenderer<Site>());
#spandel
combo5.setPrototypeDisplayValue(new Site(TITLE, new DummyIcon(Color.GRAY)));
#spanend
#spanadd
combo5.setPrototypeDisplayValue(new Site(TITLE, new ColorIcon(Color.GRAY)));
#spanend
View in GitHub: Java, Kotlin

解説

  1. デフォルト
    • モデルの中からサイズが最大となる要素を検索し、JComboBoxの推奨サイズを決定する
    • 上記のサンプルでは、モデルが空なのでボタンの幅と余白がJComboBoxの推奨サイズになっている
  2. JComboBox#setPrototypeDisplayValue(...)で指定した要素から、JComboBoxの推奨サイズを決定する
    • モデルの中からサイズが最大となる要素を検索してJComboBoxの推奨サイズを決定する
    • 上記のサンプルではモデルが空なのでボタンの幅と余白がJComboBoxの推奨サイズになっている
  3. JComboBox#setPrototypeDisplayValue(...)で指定した要素からJComboBoxの推奨サイズを決定する
  4. 編集可能な場合のJComboBoxJComboBox#setPrototypeDisplayValue(...)を設定
  5. 独自の要素Eを使用するJComboBox<E>に、その要素を表示するためのListCellRenderer<E>を設定
  6. 独自の要素Eを使用するJComboBox<E>にその要素を表示するためのListCellRenderer<E>を設定
  7. 上記のJComboBox<E>JComboBox#setPrototypeDisplayValue(E)でプロトタイプ値を設定
  8. 上記のJComboBox<E>でモデルを空にしてListCellRendererで値がnullになる場合、JComboBox#setPrototypeDisplayValue(E)で設定した値が表示されてしまう
    #spandel
    class SiteListCellRenderer<E extends Site> extends JLabel implements ListCellRenderer<E> {
    #spanend
    #spanadd
    class SiteListCellRenderer<E extends Site>
    #spanend
        extends JLabel
        implements ListCellRenderer<E> {
      @Override public Component getListCellRendererComponent(
          JList<? extends E> list, E value, int index, boolean isSelected, boolean cellHasFocus) {
          JList<? extends E> list, E value, int index,
          boolean isSelected, boolean cellHasFocus) {
        setOpaque(index >= 0);
        if (Objects.nonNull(value)) {
          setText(value.title);
          setIcon(value.favicon);
        } else {
          //JComboBox#setPrototypeDisplayValue(E)で設定した値が表示されないようにクリア
          // JComboBox#setPrototypeDisplayValue(E)で設定した値が
          // 表示されないようにクリア
          setText("");
          setIcon(null);
        }
    #spandel
    //...
    #spanend
        // ...
    

参考リンク

コメント