package jalview.io.cache; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.swing.JComboBox; import javax.swing.SwingUtilities; public class JvCacheableInputBox extends JComboBox { private static final long serialVersionUID = 5774610435079326695L; private String cacheKey; private AppCache appCache; public JvCacheableInputBox(String cacheKey) { super(); this.cacheKey = cacheKey; setEditable(true); setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); appCache = AppCache.getInstance(); appCache.initCache(cacheKey); updateCache(); } /** * Answers true if input text is an integer * * @param text * @return */ private boolean isInteger(String text) { try { Integer.parseInt(text); return true; } catch (NumberFormatException e) { return false; } } /** * Method called to update the cache with the last user input */ public void updateCache() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { String userInput = getUserInput(); if (userInput != null && !userInput.isEmpty()) { LinkedHashSet foundCache = appCache .getAllCachedItemsFor(cacheKey); // remove old cache item so as to place current input at the top of // the result foundCache.remove(userInput); foundCache.add(userInput); appCache.putCache(cacheKey, foundCache); } String lastSearch = userInput; if (getItemCount() > 0) { removeAllItems(); } Set cacheItems = appCache.getAllCachedItemsFor(cacheKey); List reversedCacheItems = new ArrayList(); reversedCacheItems.addAll(cacheItems); cacheItems = null; Collections.reverse(reversedCacheItems); if (lastSearch.isEmpty()) { addItem(""); } if (reversedCacheItems != null && !reversedCacheItems.isEmpty()) { for (String cacheItem : reversedCacheItems) { addItem(cacheItem); } } setSelectedItem(lastSearch.isEmpty() ? "" : lastSearch); } }); } public String getUserInput() { return getEditor().getItem() == null ? "" : getEditor().getItem() .toString().trim(); } }