package ballwar.view; import javax.swing.*; /** * A generic JComponent for the GUI used to select from a drop-list of possible options. */ public class OptionPanel extends Box { /** * */ private static final long serialVersionUID = 457346703351306663L; /** * The drop-list holds all the items. */ private JComboBox cBox; /** * The constructor for the class. * @param name The name of the group option values the user is choosing from. * @param items An array of items from which the user can choose. The toString() output from each item will be displayed on the drop-list. */ public OptionPanel(String name, Object... items) { super(BoxLayout.Y_AXIS); init(name, items); } private void init(String name, Object... items){ JLabel lbl = new JLabel(name); lbl.setAlignmentX((float)0.0); cBox = new JComboBox(items); cBox.setAlignmentX((float)0.0); add(lbl); add(cBox); } /** * Returns the selected item from the drop list without removing it from the list. * @return The selected item. */ public Object getSelectedItem() { return cBox.getSelectedItem(); } /** * Returns the selected item from the list and removes it from the list. This is useful * in situations where an item can only be selected once, e.g. a set of movement keys for a player. * @return The selected item. */ public Object removeSelectedItem() { Object item = cBox.getSelectedItem(); cBox.removeItem(item); return item; } /** * Adds the given item to the drop-list. The new item is added to the end of the list. * @param item The new item for the drop list. */ public void addItem(Object item) { cBox.addItem(item); } /** * Remove all the items from the list. */ public void clearItems() { cBox.removeAllItems(); } }