001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.history;
003
004import java.util.HashSet;
005import java.util.Set;
006
007import javax.swing.DefaultListSelectionModel;
008import javax.swing.ListSelectionModel;
009import javax.swing.event.ListSelectionEvent;
010import javax.swing.event.ListSelectionListener;
011
012public class SelectionSynchronizer implements ListSelectionListener {
013
014    private final Set<ListSelectionModel> participants;
015    private boolean preventRecursion;
016
017    /**
018     * Constructs a new {@code SelectionSynchronizer}.
019     */
020    public SelectionSynchronizer() {
021        participants = new HashSet<>();
022    }
023
024    public void participateInSynchronizedSelection(ListSelectionModel model) {
025        if (model == null)
026            return;
027        if (participants.contains(model))
028            return;
029        participants.add(model);
030        model.addListSelectionListener(this);
031    }
032
033    @Override
034    public void valueChanged(ListSelectionEvent e) {
035        if (preventRecursion) {
036            return;
037        }
038        preventRecursion = true;
039        DefaultListSelectionModel referenceModel = (DefaultListSelectionModel) e.getSource();
040        int i = referenceModel.getMinSelectionIndex();
041        for (ListSelectionModel model : participants) {
042            if (model == e.getSource()) {
043                continue;
044            }
045            model.setSelectionInterval(i, i);
046        }
047        preventRecursion = false;
048    }
049}