Swing/PrototypeDisplayValue のバックアップ差分(No.6)
- バックアップ一覧
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- バックアップ を表示
- Swing/PrototypeDisplayValue へ行く。
- 追加された行はこの色です。
- 削除された行はこの色です。
---
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
---
* 概要 [#summary]
`JComboBox`がそのセルサイズを決定するために使用するプロトタイプ値を設定します。
#download(https://lh3.googleusercontent.com/-DafUFitik9w/VVidadY7TNI/AAAAAAAAN4U/D40YKz8mMUY/s800/PrototypeDisplayValue.png)
* サンプルコード [#sourcecode]
#code(link){{
combo3.setPrototypeDisplayValue(TITLE);
//...
combo5.setRenderer(new SiteListCellRenderer<Site>());
combo5.setPrototypeDisplayValue(new Site(TITLE, new DummyIcon(Color.GRAY)));
}}
* 解説 [#explanation]
+ デフォルト
-- モデルの中からサイズが最大となる要素を検索し、`JComboBox`の推奨サイズを決定する
-- 上記のサンプルでは、モデルが空なのでボタンの幅と余白が`JComboBox`の推奨サイズになっている
+ `JComboBox#setPrototypeDisplayValue(...)`で指定した要素から、`JComboBox`の推奨サイズを決定する
+ 編集可能な場合の`JComboBox`に`JComboBox#setPrototypeDisplayValue(...)`を設定
-- [https://bugs.openjdk.java.net/browse/JDK-6422966 Bug ID: JDK-6422966 Editable JComboBox.setPrototypeDisplayValue: size can not be smaller than editor]
+ 独自の要素`E`を使用する`JComboBox<E>`に、その要素を表示するための`ListCellRenderer<E>`を設定
+ 上記の`JComboBox<E>`に`JComboBox#setPrototypeDisplayValue(E)`でプロトタイプ値を設定
+ 上記の`JComboBox<E>`でモデルを空にして`ListCellRenderer`で値が`null`になる場合、`JComboBox#setPrototypeDisplayValue(E)`で設定した値が表示されてしまう
#code{{
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);
}
//...
}}
* 参考リンク [#reference]
- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/JComboBox.html#setPrototypeDisplayValue-E- JComboBox#setPrototypeDisplayValue(E) (Java Platform SE 8)]
- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/JList.html#setPrototypeCellValue-E- JList#setPrototypeCellValue(E) (Java Platform SE 8)]
- [[JListがJScrollPane内に組み込まれている場合のビューポートサイズを設定する>Swing/VisibleListSizeInScrollPane]]
- [[JComboBoxなどの幅をカラム数で指定>Swing/SetColumns]]
* コメント [#comment]
#comment
#comment