source: josm/trunk/src/org/openstreetmap/josm/gui/history/SelectionSynchronizer.java@ 17994

Last change on this file since 17994 was 17773, checked in by simon04, 3 years ago

see #20745 - Introduce TableHelper.selectedIndices

  • Property svn:eol-style set to native
File size: 2.3 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.history;
3
4import java.util.HashSet;
5import java.util.Objects;
6import java.util.Set;
7import java.util.function.BiFunction;
8import java.util.stream.IntStream;
9
10import javax.swing.ListSelectionModel;
11import javax.swing.event.ListSelectionEvent;
12import javax.swing.event.ListSelectionListener;
13
14import org.openstreetmap.josm.gui.util.TableHelper;
15
16/**
17 * Helper class to ensure that two (or more) {@link javax.swing.JTable}s always
18 * have the same entries selected.
19 *
20 * The tables are usually displayed side-by-side.
21 */
22public class SelectionSynchronizer implements ListSelectionListener {
23
24 private final Set<ListSelectionModel> participants;
25 private boolean preventRecursion;
26 private BiFunction<Integer, ListSelectionModel, IntStream> selectionIndexMapper = (i, model) -> IntStream.of(i);
27
28 /**
29 * Constructs a new {@code SelectionSynchronizer}.
30 */
31 public SelectionSynchronizer() {
32 participants = new HashSet<>();
33 }
34
35 /**
36 * Add {@link ListSelectionModel} of the table to participate in selection
37 * synchronization.
38 *
39 * Call this method for all tables that should have their selection synchronized.
40 * @param model the selection model of the table
41 */
42 public void participateInSynchronizedSelection(ListSelectionModel model) {
43 if (model == null)
44 return;
45 if (participants.contains(model))
46 return;
47 participants.add(model);
48 model.addListSelectionListener(this);
49 }
50
51 void setSelectionIndexMapper(BiFunction<Integer, ListSelectionModel, IntStream> selectionIndexMapper) {
52 this.selectionIndexMapper = Objects.requireNonNull(selectionIndexMapper);
53 }
54
55 @Override
56 public void valueChanged(ListSelectionEvent e) {
57 if (preventRecursion) {
58 return;
59 }
60 preventRecursion = true;
61 ListSelectionModel referenceModel = (ListSelectionModel) e.getSource();
62 for (ListSelectionModel model : participants) {
63 if (model == referenceModel) {
64 continue;
65 }
66 TableHelper.setSelectedIndices(model,
67 TableHelper.selectedIndices(referenceModel).flatMap(i -> selectionIndexMapper.apply(i, referenceModel)));
68 }
69 preventRecursion = false;
70 }
71}
Note: See TracBrowser for help on using the repository browser.