Swing/CheckBoxForMultipleSelectionsInListCell の変更点
- 追加された行はこの色です。
- 削除された行はこの色です。
- Swing/CheckBoxForMultipleSelectionsInListCell へ行く。
- Swing/CheckBoxForMultipleSelectionsInListCell の差分を削除
--- category: swing folder: CheckBoxForMultipleSelectionsInListCell title: JListのセルにJCheckBoxを追加しマウス操作のみでの複数選択を可能にする tags: [JList, JCheckBox] author: aterai pubdate: 2025-09-29T01:26:58+09:00 description: JListのセルにJCheckBoxを追加し、これをマウスでクリックするとセルの選択・解除が可能になるよう設定します。 image: https://drive.google.com/uc?id=16ajpRoiXha8UyLtOVhkZiLdq5w1LKnsA --- * Summary [#summary] `JList`のセルに`JCheckBox`を追加し、これをマウスでクリックするとセルの選択・解除が可能になるよう設定します。 #download(https://drive.google.com/uc?id=16ajpRoiXha8UyLtOVhkZiLdq5w1LKnsA) * Source Code Examples [#sourcecode] #code(link){{ private void cellPressed(MouseEvent e, int index) { if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() > 1) { ListItem item = getModel().getElementAt(index); JOptionPane.showMessageDialog(getRootPane(), item.getTitle()); } else { checkedIndex = -1; getCheckBoxAt(e, index).ifPresent(button -> { checkedIndex = index; if (isSelectedIndex(index)) { removeSelectionInterval(index, index); } else { setSelectionInterval(index, index); } }); } } private Optional<Component> getCheckBoxAt(MouseEvent e, int index) { JList<E> list = RubberBandSelectionList.this; boolean b = e.isShiftDown() || e.isControlDown() || e.isAltDown(); return b ? Optional.empty() : getDeepestBoxAt(list, index, e.getPoint()); } private Optional<Component> getDeepestBoxAt(JList<E> list, int index, Point pt) { E proto = list.getPrototypeCellValue(); ListCellRenderer<? super E> cr = list.getCellRenderer(); Component c = cr.getListCellRendererComponent(list, proto, index, false, false); Rectangle r = list.getCellBounds(index, index); c.setBounds(r); pt.translate(-r.x, -r.y); return Optional.ofNullable(SwingUtilities.getDeepestComponentAt(c, pt.x, pt.y)) .filter(b -> b instanceof JCheckBox || b instanceof Box.Filler); } }} * Description [#description] - 左: デフォルトの`JList`で複数選択する場合はKBD{Ctrl+クリック}のようにキーボードとマウス操作を組み合わせて使用する必要がある - 右: セル選択、セル選択解除を実行する機能は[[JListのセルに項目選択チェックボックスを追加する>Swing/ListCellItemCheckBoxes]]で使用した`MouseListener`とほぼ同じ - 右: セル選択とセル選択解除を実行する機能は[[JListのセルに項目選択チェックボックスを追加する>Swing/ListCellItemCheckBoxes]]で使用した`MouseListener`とほぼ同じ -- 範囲選択機能などは除去している -- セルがクリックされたときその位置に存在するコンポーネントを検索する方法もほぼ同様で`SwingUtilities.getDeepestComponentAt(...)`メソッドを使用しているが、こちらのサンプルでは`JCheckBox`を非表示にする場合は代わりに`Box.Filler`を追加してセルとラベルの間隔を維持するセルレンダラーを作成しているため、クリック位置の最深部のコンポーネントが`Box.Filler`の場合も`JCheckBox`がクリックされたと判断している -- セルがクリックされたときその位置に存在するコンポーネントを検索する方法も同様に`SwingUtilities.getDeepestComponentAt(...)`メソッドを使用しているが、こちらのサンプルでは`JCheckBox`を非表示にする場合は代わりに`Box.Filler`を追加してセルとラベルの間隔を維持するセルレンダラーを作成しているため、クリック位置の最深部のコンポーネントが`Box.Filler`の場合も`JCheckBox`がクリックされたと判断している * Reference [#reference] - [[JListをマウスクリックのみで複数選択する>Swing/ListMouseSelection]] - [[JListのセルに項目選択チェックボックスを追加する>Swing/ListCellItemCheckBoxes]] * Comment [#comment] #comment #comment