import java.awt.Dimension;
import java.awt.FlowLayout;
-import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
+import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AbstractDocument;
public class EnsemblSpeciesDemo
{
+ private boolean updating;
+
+ private Comparator<EnsemblTaxon> byDisplayName = new Comparator<EnsemblTaxon>()
+ {
+ @Override
+ public int compare(EnsemblTaxon o1, EnsemblTaxon o2)
+ {
+ return o1.displayName.compareTo(o2.displayName);
+ }
+ };
+
/**
* Main method may be run interactively to explore a dynamic drop-down list that
* populates with matches of Ensembl taxon ids, names or aliases
@Override
public void run()
{
- createAndShowGUI();
+ new EnsemblSpeciesDemo().createAndShowGUI();
}
});
}
* Create the GUI and show it. For thread safety, this method should be invoked
* from the event dispatch thread.
*/
- private static void createAndShowGUI()
+ private void createAndShowGUI()
{
JFrame frame = new JFrame("Taxon drop-down demo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
* @param combo
* @param document
*/
- protected static void refreshComboList(JComboBox<String> combo, AbstractDocument document)
+ protected void refreshComboList(JComboBox<String> combo,
+ AbstractDocument document)
{
+ if (updating)
+ {
+ return;
+ }
+
String typed = (String) combo.getEditor().getItem();
- if (typed.length() > 1)
+ if (typed.length() > 0)
{
+ updating = true;
List<EnsemblTaxon> matches = EnsemblSpecies.getSpecies(true)
.getNameMatches(typed);
- String[] items = new String[matches.size()];
- int i = 0;
+ Collections.sort(matches, byDisplayName);
+ String[] items = new String[matches.size() + 1];
+ items[0] = typed;
+ int i = 1;
for (EnsemblTaxon m : matches)
{
items[i++] = String.format("%s (%s)", m.displayName, m.ncbiId);
}
- Arrays.sort(items, String.CASE_INSENSITIVE_ORDER);
- combo.setModel(new DefaultComboBoxModel<>(items));
+
+ /*
+ * can't update while handling a notification
+ */
+ SwingUtilities.invokeLater(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ combo.setModel(new DefaultComboBoxModel<>(items));
+ updating = false;
+ }
+ });
}
}
}