package jalview.ext.ensembl; import jalview.ext.ensembl.EnsemblSpecies.EnsemblTaxon; import java.awt.Dimension; import java.awt.FlowLayout; import java.util.Arrays; import java.util.List; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.AbstractDocument; import javax.swing.text.JTextComponent; public class EnsemblSpeciesDemo { /** * Main method may be run interactively to explore a dynamic drop-down list that * populates with matches of Ensembl taxon ids, names or aliases * * @param args */ public static void main(String[] args) { // Schedule a job for the event dispatch thread: // creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } /** * Create the GUI and show it. For thread safety, this method should be invoked * from the event dispatch thread. */ private static void createAndShowGUI() { JFrame frame = new JFrame("Taxon drop-down demo"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JComponent newContentPane = new JPanel(new FlowLayout()); newContentPane.setOpaque(true); newContentPane.setPreferredSize(new Dimension(400, 300)); frame.setContentPane(newContentPane); JLabel label = new JLabel("Taxon:"); newContentPane.add(label); JComboBox combo = new JComboBox<>(); combo.setEditable(true); combo.setPreferredSize(new Dimension(200, 20)); newContentPane.add(combo); AbstractDocument document = (AbstractDocument) ((JTextComponent) combo .getEditor().getEditorComponent()).getDocument(); document.addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { refreshComboList(combo, document); } @Override public void removeUpdate(DocumentEvent e) { refreshComboList(combo, document); } @Override public void changedUpdate(DocumentEvent e) { } }); frame.pack(); frame.setVisible(true); } /** * Refreshes the combo box list to contain what the user has typed, plus any * matches for Ensembl taxon id, name or alias * * @param combo * @param document */ protected static void refreshComboList(JComboBox combo, AbstractDocument document) { String typed = (String) combo.getEditor().getItem(); if (typed.length() > 1) { List matches = EnsemblSpecies.getSpecies(true) .getNameMatches(typed); String[] items = new String[matches.size()]; int i = 0; 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)); } } }