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
016    /**
017     * Constructs a new {@code SelectionSynchronizer}.
018     */
019    public SelectionSynchronizer() {
020        participants = new HashSet<>();
021    }
022
023    public void participateInSynchronizedSelection(ListSelectionModel model) {
024        if (model == null)
025            return;
026        if (participants.contains(model))
027            return;
028        participants.add(model);
029        model.addListSelectionListener(this);
030    }
031
032    @Override
033    public void valueChanged(ListSelectionEvent e) {
034        DefaultListSelectionModel referenceModel = (DefaultListSelectionModel) e.getSource();
035        int i = referenceModel.getMinSelectionIndex();
036        for (ListSelectionModel model : participants) {
037            if (model == e.getSource()) {
038                continue;
039            }
040            model.setSelectionInterval(i, i);
041        }
042    }
043}