• 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);
//...
combo5.setRenderer(new SiteListCellRenderer<Site>());
combo5.setPrototypeDisplayValue(new Site(TITLE, new DummyIcon(Color.GRAY)));
View in GitHub: Java, Kotlin

解説

  1. デフォルトのJComboBoxで、モデルの中からサイズが最大となる要素を検索し、JComboBoxの推奨サイズを決定する
  2. JComboBox#setPrototypeDisplayValue(...)で指定した要素から、JComboBoxの推奨サイズを決定する
  3. 編集可能な場合のJComboBoxJComboBox#setPrototypeDisplayValue(...)を設定
    1. Bug ID: JDK-6422966 Editable JComboBox.setPrototypeDisplayValue: size can not be smaller than editor
  4. 独自の要素Eを使用するJComboBox<E>に、その要素を表示するためのListCellRenderer<E>を設定
  5. 上記のJComboBox<E>JComboBox#setPrototypeDisplayValue(E)でプロトタイプ値を設定
  6. 上記のJComboBox<E>でモデルを空にしてListCellRendererで値がnullになる場合、JComboBox#setPrototypeDisplayValue(E)で設定した値が表示されてしまう
    class SiteListCellRenderer<E extends Site> extends JLabel implements ListCellRenderer<E> {
      @Override public Component getListCellRendererComponent(
          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)で設定した値が表示されないようにクリア
          setText("");
          setIcon(null);
        }
    //...
    

参考リンク

コメント