package util; // Java imports import java.awt.event.*; import java.util.*; import javax.swing.*; // Wrapper around JComboBox to enforce desired behaviors public class UComboBox extends JComboBox { // Instance fields private HashMap actionListeners; /////////////////////////////////////////////////////////////////////////// // Constants // /////////////////////////////////////////////////////////////////////////// // Empty item set private static final String[] EMPTY = new String[0]; /////////////////////////////////////////////////////////////////////////// // Constructors // /////////////////////////////////////////////////////////////////////////// // Default constructor public UComboBox() { this(null); } // List constructor public UComboBox(String[] items) { super(); actionListeners = new HashMap(); setItems(items); } /////////////////////////////////////////////////////////////////////////// // Public Methods // /////////////////////////////////////////////////////////////////////////// // Add a listener to receive action events public void addActionListener(ActionListener l) { // Error checking if (l == null) return; // Wrap the event listener in a guard ActionListener L = e->{ // Search the stack trace for an invocation not from Java itself var trace = Thread.currentThread().getStackTrace(); for (int x = 2; x < trace.length; x++) if (trace[x].getModuleName() == null) return; // Call the event handler l.actionPerformed(e); }; // Manage the collections actionListeners.put(l, L); super.addActionListener(L); } // Retrieve a list of the current action listeners public ActionListener[] getActionListeners() { return actionListeners.keySet().toArray( new ActionListener[actionListeners.size()]); } // Remove an action listener from the collection public void removeActionListener(ActionListener l) { var L = actionListeners.get(l); if (L == null) return; actionListeners.remove(l); super.removeActionListener(L); } // Update the items in the list public void setItems(String[] items) { int index = getSelectedIndex(); setModel(new DefaultComboBoxModel( items != null ? items : EMPTY)); setSelectedIndex(index); } }