package xyz.danielcortes.framework;

import java.util.Set;
import javax.swing.JList;
import javax.swing.ListModel;

public class JListUtils {
  public static void setSelectedValues(JList list, Set values) {
    list.clearSelection();
    for (Object value : values) {
      int index = getIndex(list.getModel(), value);
      if (index >= 0) {
        list.addSelectionInterval(index, index);
      }
    }
    list.ensureIndexIsVisible(list.getSelectedIndex());
  }

  private static int getIndex(ListModel model, Object value) {
    if (value == null) {
      return -1;
    }
    for (int i = 0; i < model.getSize(); i++) {
      if (value.equals(model.getElementAt(i)))
        return i;
    }
    return -1;
  }
}
