package com.ts3client.ui; import com.ts3client.config.IdentityEntry; import com.ts3client.config.IdentityStore; import javax.swing.DefaultListCellRenderer; import javax.swing.JComboBox; import javax.swing.JList; import java.awt.Component; /** * Drop-down for picking the identity to connect with. Optionally offers a * "use the default identity" entry for places where the choice may stay unset * (bookmarks), so changing the default later applies retroactively. */ final class IdentityChooser extends JComboBox { private static final String USE_DEFAULT = "‹Default identity›"; private final IdentityStore identities; private final boolean allowDefault; IdentityChooser(IdentityStore identities, boolean allowDefault, String selectedId) { this.identities = identities; this.allowDefault = allowDefault; if (allowDefault) addItem(USE_DEFAULT); for (IdentityEntry e : identities.all()) addItem(e); setSelectedIdentityId(selectedId); setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { String text = value instanceof IdentityEntry ? ((IdentityEntry) value).getName() : String.valueOf(value); return super.getListCellRendererComponent(list, text, index, isSelected, cellHasFocus); } }); } /** Selected identity id, or an empty string when the default is to be used. */ String getSelectedIdentityId() { Object v = getSelectedItem(); return v instanceof IdentityEntry ? ((IdentityEntry) v).getId() : ""; } /** Selects the identity with the given id, falling back to the default entry. */ void setSelectedIdentityId(String id) { IdentityEntry selected = identities.byId(id); if (selected != null) { setSelectedItem(selected); } else if (allowDefault) { setSelectedItem(USE_DEFAULT); } } }