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 | /**
|
---|
13 | * Helper class to ensure that two (or more) {@link javax.swing.JTable}s always
|
---|
14 | * have the same entries selected.
|
---|
15 | *
|
---|
16 | * The tables are usually displayed side-by-side.
|
---|
17 | */
|
---|
18 | public class SelectionSynchronizer implements ListSelectionListener {
|
---|
19 |
|
---|
20 | private final Set<ListSelectionModel> participants;
|
---|
21 | private boolean preventRecursion;
|
---|
22 |
|
---|
23 | /**
|
---|
24 | * Constructs a new {@code SelectionSynchronizer}.
|
---|
25 | */
|
---|
26 | public SelectionSynchronizer() {
|
---|
27 | participants = new HashSet<>();
|
---|
28 | }
|
---|
29 |
|
---|
30 | /**
|
---|
31 | * Add {@link ListSelectionModel} of the table to participate in selection
|
---|
32 | * synchronization.
|
---|
33 | *
|
---|
34 | * Call this method for all tables that should have their selection synchronized.
|
---|
35 | * @param model the selection model of the table
|
---|
36 | */
|
---|
37 | public void participateInSynchronizedSelection(ListSelectionModel model) {
|
---|
38 | if (model == null)
|
---|
39 | return;
|
---|
40 | if (participants.contains(model))
|
---|
41 | return;
|
---|
42 | participants.add(model);
|
---|
43 | model.addListSelectionListener(this);
|
---|
44 | }
|
---|
45 |
|
---|
46 | @Override
|
---|
47 | public void valueChanged(ListSelectionEvent e) {
|
---|
48 | if (preventRecursion) {
|
---|
49 | return;
|
---|
50 | }
|
---|
51 | preventRecursion = true;
|
---|
52 | DefaultListSelectionModel referenceModel = (DefaultListSelectionModel) e.getSource();
|
---|
53 | int i = referenceModel.getMinSelectionIndex();
|
---|
54 | for (ListSelectionModel model : participants) {
|
---|
55 | if (model == e.getSource()) {
|
---|
56 | continue;
|
---|
57 | }
|
---|
58 | model.setSelectionInterval(i, i);
|
---|
59 | }
|
---|
60 | preventRecursion = false;
|
---|
61 | }
|
---|
62 | }
|
---|