[2512] | 1 | // License: GPL. For details, see LICENSE file.
|
---|
| 2 | package org.openstreetmap.josm.gui.history;
|
---|
| 3 |
|
---|
[8390] | 4 | import java.util.HashSet;
|
---|
| 5 | import java.util.Set;
|
---|
[2512] | 6 |
|
---|
| 7 | import javax.swing.DefaultListSelectionModel;
|
---|
| 8 | import javax.swing.ListSelectionModel;
|
---|
| 9 | import javax.swing.event.ListSelectionEvent;
|
---|
| 10 | import javax.swing.event.ListSelectionListener;
|
---|
| 11 |
|
---|
[12615] | 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 | */
|
---|
[2512] | 18 | public class SelectionSynchronizer implements ListSelectionListener {
|
---|
| 19 |
|
---|
[8390] | 20 | private final Set<ListSelectionModel> participants;
|
---|
[10755] | 21 | private boolean preventRecursion;
|
---|
[2512] | 22 |
|
---|
[6316] | 23 | /**
|
---|
| 24 | * Constructs a new {@code SelectionSynchronizer}.
|
---|
| 25 | */
|
---|
[2512] | 26 | public SelectionSynchronizer() {
|
---|
[8390] | 27 | participants = new HashSet<>();
|
---|
[2512] | 28 | }
|
---|
| 29 |
|
---|
[12615] | 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 | */
|
---|
[2512] | 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 |
|
---|
[6084] | 46 | @Override
|
---|
[2512] | 47 | public void valueChanged(ListSelectionEvent e) {
|
---|
[10637] | 48 | if (preventRecursion) {
|
---|
| 49 | return;
|
---|
| 50 | }
|
---|
| 51 | preventRecursion = true;
|
---|
[8510] | 52 | DefaultListSelectionModel referenceModel = (DefaultListSelectionModel) e.getSource();
|
---|
[2512] | 53 | int i = referenceModel.getMinSelectionIndex();
|
---|
| 54 | for (ListSelectionModel model : participants) {
|
---|
| 55 | if (model == e.getSource()) {
|
---|
| 56 | continue;
|
---|
| 57 | }
|
---|
[8510] | 58 | model.setSelectionInterval(i, i);
|
---|
[2512] | 59 | }
|
---|
[10637] | 60 | preventRecursion = false;
|
---|
[2512] | 61 | }
|
---|
| 62 | }
|
---|