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