Swing/ClearSelection のバックアップ(No.17)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/ClearSelection へ行く。
- 1 (2011-04-18 (月) 14:47:37)
- 2 (2011-04-19 (火) 13:59:30)
- 3 (2012-12-22 (土) 15:58:00)
- 4 (2014-11-12 (水) 02:09:03)
- 5 (2015-01-22 (木) 21:18:17)
- 6 (2015-02-18 (水) 15:04:15)
- 7 (2016-12-03 (土) 18:28:31)
- 8 (2017-04-04 (火) 14:17:08)
- 9 (2017-12-01 (金) 13:21:53)
- 10 (2019-08-08 (木) 18:57:58)
- 11 (2021-04-09 (金) 19:43:33)
- 12 (2021-11-24 (水) 06:33:00)
- 13 (2025-01-03 (金) 08:57:02)
- 14 (2025-01-03 (金) 09:01:23)
- 15 (2025-01-03 (金) 09:02:38)
- 16 (2025-01-03 (金) 09:03:21)
- 17 (2025-01-03 (金) 09:04:02)
- category: swing
folder: ClearSelection
title: JListの選択を解除
tags: [JList, Focus, MouseListener]
author: aterai
pubdate: 2011-04-18T14:47:37+09:00
description: JListのセル選択状態をセル以外の余白領域をクリックすることで解除できるように設定します。
image:
Summary
JList
のセル選択状態をセル以外の余白領域をクリックすることで解除できるように設定します。
Screenshot

Advertisement
Source Code Examples
class ClearSelectionListener extends MouseInputAdapter {
private boolean startOutside;
private static <E> void clearSelectionAndFocus(JList<E> list) {
list.clearSelection();
list.getSelectionModel().setAnchorSelectionIndex(-1);
list.getSelectionModel().setLeadSelectionIndex(-1);
}
private static <E> boolean contains(JList<E> list, Point pt) {
for (int i = 0; i < list.getModel().getSize(); i++) {
if (list.getCellBounds(i, i).contains(pt)) {
return true;
}
}
return false;
}
@Override public void mousePressed(MouseEvent e) {
JList<?> list = (JList<?>) e.getComponent();
startOutside = !contains(list, e.getPoint());
if (startOutside) {
clearSelectionAndFocus(list);
}
}
@Override public void mouseReleased(MouseEvent e) {
startOutside = false;
}
@Override public void mouseDragged(MouseEvent e) {
JList<?> list = (JList<?>) e.getComponent();
if (contains(list, e.getPoint())) {
startOutside = false;
} else if (startOutside) {
clearSelectionAndFocus(list);
}
}
}
View in GitHub: Java, KotlinExplanation
上記のサンプルでは、JList
のセル以外の領域をクリックするとすべてのセルの選択とフォーカスを解除するようにマウスリスナーなどを設定しています。
- 選択解除
JList#clearSelection();
ListSelectionModel#clearSelection()
のカバーメソッド
- フォーカス解除
list.getSelectionModel().setAnchorSelectionIndex(-1);
list.getSelectionModel().setLeadSelectionIndex(-1);
- アンカー(アイテムのハイライト)、リード(アイテムのフォーカス)の順番で解除する必要がある
Reference
- How to Write a List Selection Listener (The Java™ Tutorials > Creating a GUI With JFC/Swing > Writing Event Listeners)
- JList#clearSelection() (Java Platform SE 8)
- ListSelectionModel#clearSelection() (Java Platform SE 8)