package com.onaro.sanscreen.client.view.actions.application; import java.awt.Component; import java.util.Arrays; import java.util.List; import javax.swing.DefaultListCellRenderer; import javax.swing.JComboBox; import javax.swing.JList; import org.apache.commons.lang3.StringUtils; import com.onaro.sanscreen.server.interfaces.data.inventory.BusinessEntity; /** * Represents a combobox of BusinessEntity objects. Formats BEs as tenant.lob.bu.project. * * @author rnoel * */ public class BusinessEntityComboPicker extends JComboBox { private static final long serialVersionUID = 1L; // If true then add a N/A BE to the list. private boolean addNaBE; public BusinessEntityComboPicker(boolean addNaBE) { this(new BusinessEntity[0], addNaBE); } public BusinessEntityComboPicker(BusinessEntity[] bes, boolean addNaBE) { this(Arrays.asList(bes), addNaBE); } public BusinessEntityComboPicker(List bes, boolean addNaBE) { this.addNaBE = addNaBE; setRenderer(new BERenderer()); setBusinessEntities(bes); } public void setBusinessEntities(List bes) { removeAllItems(); if (addNaBE) { addItem(BusinessEntityUtils.NA_BUSINESS_ENTITY); } for (BusinessEntity be : bes) { addItem(be); } } /* Sets the selected BE to the one that matches the given BE or do nothing if a matching BE could not be found. */ protected void selectBusinessEntity(BusinessEntity be) { setSelectBusinessEntityById(be.getId()); } /* Sets the selected BE to the one that matches the given ID or do nothing if a matching ID could not be found. */ protected void setSelectBusinessEntityById(Long id) { if (id == null) { return; } int beCount = getItemCount(); for (int i = 0; i < beCount; i++) { BusinessEntity be = getItemAt(i); if (id.equals(be.getId())) { setSelectedIndex(i); break; } } } /** * * @return the selected BusinessEntity in the combobox or null if nothing is selected. */ public BusinessEntity getSelectedBusinessEntity() { return ((BusinessEntity) getSelectedItem()); } private static class BERenderer extends DefaultListCellRenderer { private static final long serialVersionUID = 1L; @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { BusinessEntity be = (BusinessEntity) value; String displayValue = StringUtils.EMPTY; if (be != null) { displayValue = BusinessEntityUtils.formatBusinessEntity(be); } return super.getListCellRendererComponent(list, displayValue, index, isSelected, cellHasFocus); } } }