001package jmri.jmrix.openlcb.swing.protocoloptions;
002
003import java.util.Collection;
004
005import javax.swing.JButton;
006import javax.swing.JComponent;
007
008import jmri.jmrix.AbstractConnectionConfig;
009import jmri.jmrix.can.CanSystemConnectionMemo;
010import jmri.jmrix.openlcb.configurexml.ConnectionConfigXml;
011
012/**
013 * Helper class for implementing OpenLCB compatible port adapters. Common code for those adapters
014 * is factored out into functions in this class.
015 *
016 * @author Balazs Racz, (C) 2018.
017 */
018
019public class ConfigPaneHelper {
020    /**
021     * Adds a button to the connection config setup panel that opens the openLCB protocol options.
022     * Does nothing if the adapter is not being used in OpenLCB mode.
023     *
024     * Helper function in the ConnectionConfig.loadDetails() function for OpenLCB compatible
025     * adapter configs. The loadDetails() function needs to be overridden with the following
026     * code:
027     * <code>
028     *     public void loadDetails(JPanel details) {
029     *         setInstance();
030     *         ConfigPaneHelper.maybeAddOpenLCBProtocolOptionsButton(this, additionalItems);
031     *         super.loadDetails(details);
032     *     }
033     * </code>
034     *
035     * @param connection the ConnectionConfig for the particular adapter calling.
036     * @param additionalItems reference to the inherited additionalItems list from the
037     *                        AbstractConnectionConfig. The helper funciton will modify it in
038     *                        place.
039     */
040    public static void maybeAddOpenLCBProtocolOptionsButton(AbstractConnectionConfig connection, Collection<JComponent> additionalItems) {
041        // Checks if we are using OpenLCB protocol.
042        CanSystemConnectionMemo sc = ConnectionConfigXml.isOpenLCBProtocol(connection.getAdapter());
043        if (sc == null) return;
044        // Checks if the button already exists in the panel.
045        String label = Bundle.getMessage("ProtocolOptionsButton");
046        for (JComponent c : additionalItems) {
047            if (!(c instanceof JButton)) {
048                continue;
049            }
050            if (((JButton) c).getText().equals(label)) {
051                return; // button already exists
052            }
053        }
054        // Creates and adds the button.
055        JButton b = new JButton(label);
056        b.addActionListener(new ProtocolOptionsAction(sc));
057        additionalItems.add(b);
058    }
059}