---
category: swing
folder: DisabledItem
title: JListの任意のItemを選択不可にする
tags: [JList, ListCellRenderer, ActionMap]
author: aterai
pubdate: 2005-05-30T09:46:59+09:00
description: JListの任意のItemを選択不可にするListCellRendererを設定します。
image: https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTLAYVmo3I/AAAAAAAAAW4/3MUtTm4ixyo/s800/DisabledItem.png
hreflang:
href: https://java-swing-tips.blogspot.com/2017/04/disable-any-items-in-jlist.html
lang: en
---
* Summary [#summary]
`JList`の任意の`Item`を選択不可にする`ListCellRenderer`を設定します。
#download(https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTLAYVmo3I/AAAAAAAAAW4/3MUtTm4ixyo/s800/DisabledItem.png)
* Source Code Examples [#sourcecode]
#code(link){{
JList<String> list = new JList<>(model);
list.setCellRenderer(new DefaultListCellRenderer() {
@Override public Component getListCellRendererComponent(
JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Component c;
if (disableIndexSet.contains(index)) {
c = super.getListCellRendererComponent(list, value, index, false, false);
c.setEnabled(false);
} else {
c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
}
return c;
}
});
ActionMap am = list.getActionMap();
am.put("selectNextRow", new AbstractAction() {
@Override public void actionPerformed(ActionEvent ae) {
for (int i = list.getSelectedIndex() + 1; i < list.getModel().getSize(); i++) {
if (!disableIndexSet.contains(Integer.valueOf(i))) {
list.setSelectedIndex(i);
break;
}
}
}
});
}}
* Description [#explanation]
* Description [#description]
- `JList`のアイテムの選択可・不可はリストセルレンダラーの`ListCellRenderer#getListCellRendererComponent(...)`メソッド中で判断する
- インデックスが選択不可の場合オリジナルのリストセルレンダラーから選択無し、かつフォーカス無しのコンポーネントを取得し、さらに`setEnabled(false)`として返す
- KBD{Up}、KBD{Down}キーで`JList`のアイテムの選択を移動する場合、選択不可にしたアイテムを飛ばすように`selectNextRow`などのアクションを変更
* Reference [#reference]
- [[JComboBoxのアイテムを選択不可にする>Swing/DisableItemComboBox]]
* Comment [#comment]
#comment
#comment